我正在第一个包含JSON数据的Vue.js项目,该数据应该由几个属性过滤。 我需要对Vue.js进行复选框过滤。我有两个。它们分开工作,但是当我尝试将它们组合时,它们就没有作用。这是我的代码:
<template>
<div id="app1">
<div v-for="userId in userIds" class="check-userid">
<input type="checkbox" v-model="checkedUserIds" v-bind:value="userId">
{{userId}}
</div>
<br>
<div v-for="id in ids" class="check-id">
<input type="checkbox" v-model="checkedIds" v-bind:value="id">
{{id}}
</div>
<br>
<div v-for="job in filteredJobs1">
<h2>{{ job.id }}) {{ job.title }}</h2>
<div>{{ job.body }}</div>
</div>
<div v-for="job in filteredJobs2">
<h2>{{ job.id }}) {{ job.title }}</h2>
<div>{{ job.body }}</div>
</div>
</div>
</template>
import axios from "axios";
export default {
name: "Checkbox",
data() {
return {
jobs: [],
userIds: [1, 2, 3],
ids: [1, 2, 3, 4, 5, 6, 7, 8,9, 10],
checkedUserIds: [],
checkedIds: []
};
},
created() {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => (this.jobs = response.data));
},
computed: {
filteredJobs1() {
if (!this.checkedUserIds.length) return this.jobs;
return this.jobs.filter(job => this.checkedUserIds.includes(job.userId));
},
filteredJobs2() {
if (!this.checkedIds.length) return this.jobs;
return this.jobs.filter(job => this.checkedIds.includes(job.id));
}
}
};
我试图这样做,但是没有用
computed: {
filteredJobs: function() {
return this.jobs
.filter(job => this.checkedUserIds.includes(job.userId))
.filter(job => this.checkedIds.includes(job.id))
}
}
答案 0 :(得分:1)
假设如果未选中任何一个过滤器的复选框,则您不想应用该过滤器,类似的操作应该可以...
computed: {
filteredJobs () {
return this.jobs.filter(({ id, userId }) => {
return (this.checkedUserIds.length === 0 || this.checkedUserIds.includes(userId))
&& (this.checkedIds.length === 0 || this.checkedIds.includes(id))
})
}
}