所以我试图在 vue 中创建一个过滤方法,它的规则之一是过滤其公司 ID 位于过滤列表中的对象。
所以基本上用户可以选择多个公司,vue 将创建一个列表,例如 [1,5,2,6]
然后该列表被解析到 processFilter()
方法,现在应该过滤产品数组,仅包含其 company id
位于 vue 创建的列表中的产品。
产品数组示例:
[
{
'id': 1,
'name': 'Prod1',
'min_price': '1',
'max_price': '2',
'currency': 'EUR',
'image': '<Some_big_url>',
'company': '1',
'sub_category': '2',
'created': '<some_big_date>',
'views': '10000'
}
]
我的processFilter方法:
processFilter() {
const subCategory = this.filtersSub;
const company = this.filtersComp;
const sortBy = this.filtersSort;
this.filtered = this.products.filter(
this.data.includes(subCategory) && this.data.includes(company)
);
},
测试此函数方法后,它会在控制台中返回以下内容:
vue.runtime.esm.js:1888 TypeError: Cannot read property 'includes' of undefined
at a.processFilter (category.vue:227)
at submit (category.vue?c00e:1)
at ne (vue.runtime.esm.js:1854)
at HTMLFormElement.n (vue.runtime.esm.js:2179)
at HTMLFormElement.Ji.o._wrapper (vue.runtime.esm.js:6917)
有没有办法让这项工作正常进行,或者我应该以不同的方式进行?
在有人问"is"之前,我是 console.log() 公司和 this.filtersComp
,是的,它们不是 未定义
并且其中包含值,如下所示图片:
最佳答案
我不知道过滤器内部的逻辑应该如何工作,但过滤器接受回调函数,并且您在此处仅传递一个 bool 值:
this.filtered = this.products.filter(
this.data.includes(subCategory) && this.data.includes(company)
);
你可以像这样改变它:
this.filtered = this.products.filter( product => {
//if you console log here, product will be printed as many times as the
//lenght of this.products applying the boolean
console.log(product)
//return this.data.includes(subCategory) && this.data.includes(company)
//this will alway return the same value (true or false)
//probably you want to use the product in your logic
return product.sub_category.includes(subCategory) && product.company.includes(company)
});
但这没有多大意义,因为 this.data.includes(subCategory) && this.data.includes(company)
的结果在每次迭代中始终相同,从而导致所有元素是否被过滤。
您很可能需要使用 product
来实际过滤数组。
关于javascript - vue.js 中的 .includes() 和 .filter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62920847/