我正在尝试使用过滤器来展示产品。基本上,用户单击复选框,它会返回标题。
我正在尝试从称为“产品”的数组中获取数据。里面有标题。
我不能做的是,如果用户单击两个或三个复选框,则不会显示输出。相反,它变为空白。
例如,我要选择“汽车”和“房屋”。目前,我可以选择汽车或房屋。如果同时选择两者,它将消失。
将非常感谢您的帮助。
谢谢。
已编辑
我试图将其链接到filteredSearch()
下
产品数组不仅包含汽车,房屋。
P.topic在products []数组中。
data: {
products:[],
.....
computed: {
filteredProducts() {
return this.products.filter(x => x.name === this.loggedUser[0].text);
},
filteredSearch() {
return this.products
.filter(p => p.topic.toLowerCase().match(this.search.toLowerCase()))
.filter(p => p.price <= this.priceFilter)
}
答案 0 :(得分:1)
将filter
应用于数组时,实际上是在减少该数组以匹配提供的表达式。这适用于所有后续的filter
。因此,使用多个表达式执行此操作确实没有逻辑。
相反,您可以在过滤器外部收集值,并使用一种filter
方法来检查数组中每个元素的主题是否与您先前收集的任何过滤后的值相匹配。
const filterByTopic = []
this.checkBox2 && filterByTopic.push('House')
this.checkBox3 && filterByTopic.push('Car')
const filtered = myArray.filter(p => !filterByTopic.length || filterByTopic.some(val => p.topic.match(val)))
答案 1 :(得分:1)
您对filter
的第二次调用正在处理已过滤的数组。
只有与“房屋”匹配的商品现在将通过“汽车”的第二个匹配,并且由于显然没有,因此您得到的结果为空。
鉴于这是Vue,我将有一个filters
数组,我将在其中存储所有选定的过滤器。然后在computed
道具中,我将遍历所有主题并返回与filter数组中的任何filter匹配的主题。
作为一个简单的例子,还有其他一些事情需要弄清楚。
// parts of a Vue component
data: () => ({
topics: ["Houses", "Boats", "Cars", "Bicycles", "Skates"],
filters: ["Houses", "Cars"]
}),
computed: {
filteredTopics() {
return this.filters.length && this.topics.filter(topic => this.filters.includes(topic)) || this.topics
},
// or using match
matchedTopics() {
return this.filters.length && this.topics.filter(topic => this.filters.some(filter => topic.match(filter))) || this.topics
},
sortedAndMatchedTopics() {
// basically pick on the already filtered result and sort it someway, for example
return this.matchedTopics.sort( /* ... your logic for sorting here */ )
}
}
显然,这些数据与您的数据不同,因此必须对其进行调整,而且,当您选择/取消选择filters
中的项目时,还必须添加/删除这些项目。
做了一些小提琴,以更好地解释如何在Vue https://jsfiddle.net/Compay/w63yj9Lx/10/中实现这一目标