是的,又是我。我正在尝试根据字符串数组过滤数组。因此,虽然使用 Vue 很容易使用单个字符串过滤器......
<div v-for="item in items | filterBy 'words' in 'property'">
...多个搜索字符串变得更加复杂。 StackOverflow 上已经有几个关于如何执行此操作的问题,但答案很少。目前我正在尝试重新调整找到的自定义过滤器 here满足我的需要,但它不起作用。
我的用例: 我有一组组(复选框),用户可以选择它们来过滤一组人。每个人都被分配到一个或多个组,因此如果用户选择了其中任何一个组,该人就会出现。
所以我的模板如下所示:
<template v-for="group in ensemble_groups">
<input name="select_group[]" id="group_@{{ $index }}"
:value="group"
v-model="selected_groups"
type="checkbox">
<label for="group_@{{ $index }}">@{{ group }}</label>
</template>
<template v-for="person in cast | filterBy selectGroups">
<div>@{{ person.actor_name }}</div>
</template>
您看到我的自定义过滤器 selectGroups
那里?这是我的 Vue 数组:
selected_groups: [],
ensemble_groups: ["Leads","Understudies","Children","Ensemble"],
cast: [
{
actor_name: "Dave",
groups: ["Leads"],
},
{
actor_name: "Jill",
groups: ["Leads"],
},
{
actor_name: "Sam",
groups: ["Children","Ensemble"],
},
{
actor_name: "Austin",
groups: ["Understudies","Ensemble"],
},
],
最后是自定义过滤器。我无法判断它是否被触发,因为当我单击组复选框时,什么也没有发生。
filters: {
selectGroups: function() {
if (!selected_groups || selected_groups.length === 0) {
return cast;
}
return this.recursiveFilter(cast, selected_groups, 0);
}
},
methods: {
recursiveFilter: function(cast, selected_groups, currentPosition) {
if (currentPosition+1 > selected_groups.length)
return cast;
var new_cast;
new_cast = cast.filter(function(person) {
for (group of person.groups) {
if (group.value == selected_groups[currentPosition])
return true;
}
});
return this.recursiveFilter(new_cast, selected_groups, currentPosition+1);
}
}
因此,如果用户选择 Leads
只有戴夫和吉尔应该出现。如果用户随后检查 Children
、戴夫、吉尔和山姆应该出现。我已经很接近了!
最佳答案
我会使用计算属性而不是过滤器和方法。
我会检查每个 Actor ,如果他们的任何组在 selected_groups
中,我会允许其通过过滤器。我想使用 Array.some 来实现这一点。
results: function() {
var self = this
return self.cast.filter(function(person) {
return person.groups.some(function(group) {
return self.selected_groups.indexOf(group) !== 1
})
})
},
这是我设置的一个快速演示,可能有用:http://jsfiddle.net/crswll/df4Lnuw6/8/
关于javascript - Vue JS 使用数组来过滤另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049950/