Reputation: 849
I am trying to filter a list of posts using the userId in checkboxes. I am pulling the data from: https://jsonplaceholder.typicode.com/posts and want to then add checkboxes that when checked filter the list by userId. This is what I have currently:
var app = new Vue({
el: '#app',
data() {
return {
jobs: [],
userIds: ['1', '2', '3'],
checkedUserIds: []
}
},
created() {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(response => (this.jobs = response.data))
},
computed: {
filteredJobs() {
if (!this.checkedUserIds.length)
return this.jobs
return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<div v-for="userId in userIds">
<input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
</div>
<div v-for="job in filteredJobs">
<h2>{{ job.title }}</h2>
<div>{{ job.body }}</div>
</div>
</div>
I am stumped on why when I click a checkbox the whole list disappears instead of filtering by the userId
Upvotes: 1
Views: 2242
Reputation: 2131
Your userIds: ['1', '2', '3'],
is an array of strings not integers. Try userIds: [1, 2, 3],
The json file has userId
as integers. Types to need to be the same for this function to work.
var app = new Vue({
el: '#app',
data() {
return {
jobs: [],
userIds: [1,2,3],
checkedUserIds: []
}
},
created() {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(response => (this.jobs = response.data))
},
computed: {
filteredJobs() {
if (!this.checkedUserIds.length)
return this.jobs
return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<div v-for="userId in userIds">
<input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
</div>
<div v-for="job in filteredJobs">
<h2>{{ job.title }}</h2>
<div>{{ job.body }}</div>
</div>
</div>
Upvotes: 3