我正在尝试过滤Vue.js呈现的某些内容,但是只有第一个过滤器在起作用,大小过滤器。
var vm = new Vue({
el: "#full_area",
data: {
projects: <?php print json_encode($postsa);?>,
selectedSize: "All",
selectedPlatform: "All"
},
computed: {
filteredProjects: function () {
var vm = this;
var size = vm.selectedSize;
var platform = vm.selectedPlatform;
if (size === "All") {
return vm.projects;
} else if (size != "All") {
return vm.projects.filter(function (project) {
return project.size === size;
});
}
if (platform === "All") {
return vm.projects;
} else if (platform != "All") {
return vm.projects.filter(function (project) {
return project.platform === platform;
});
}
}
}
});
<div class="filter">
<select name="selectedSize" v-model="selectedSize">
<option value="All">Website Size</option>
<option>1 Page</option>
...
<option>10+ Page</option>
</select>
</div>
<div class="filter">
<select name="selectedPlatform" v-model="selectedPlatform">
<option value="All">CMS Platform</option>
<option>Wordpress</option>
.....
</select>
</div>
我已经尝试了一些与if和else一起玩的方法,但是没有运气。有什么想法吗?
谢谢。
答案 0 :(得分:1)
一种较为简单的方法:
computed: {
filteredProjects: function () {
const size = this.selectedSize,
platform = this.selectedPlatform;
return this.projects
.filter(p => size === 'All' || p.size === size)
.filter(p => platform === 'All' || p.platform === platform)
}
}
答案 1 :(得分:0)
您需要先按大小过滤,然后再按平台过滤。在当前代码中,按大小功能处理过滤器的return语句使代码无法访问。
尝试这样的事情:
filteredProjects: function () {
var vm = this;
var size = vm.selectedSize;
var platform = vm.selectedPlatform;
var filteredProjects;
// first, filter by size, saving the results to
// the variable filteredProjects
if (size === "All") {
filteredProjects = vm.projects;
} else {
filteredProjects = vm.projects.filter(function (project) {
return project.size === size;
});
}
// then, continue filtering `filteredProjects`, using the platform
if (platform === "All") {
filteredProjects = filteredProjects;
} else {
filteredProjects = filteredProjects.filter(function (project) {
return project.platform === platform;
});
}
return filteredProjects
}
我还将else if
语句更改为简单的else
。变量可以等于All
,也可以不等于-无需明确说明替代方案。