我有一些产品,我想使用复选框根据它们的类别进行筛选.
为此,我有一个父组件,它将可能的类别(例如A、B和C)传递给子组件,并跟踪选中/ Select 的类别.
然而,棘手的部分是,可能的类别是动态的:有时类别数组可能会缩小或增长.
这会导致不正确的行为,因为复选框的布尔值不再对应于正确的位置.例如,前两个复选框处于选中状态,但每当数组更改时,前两个值仍处于选中状态(它们现在是不同的值).这一点如下所示:
我设法解决了这个问题,让子元素用一个本地属性跟踪复选框本身,并在更新时发送给父母.但是,如果我添加了第二个子项,则子项1和子项2不再同步(例如,当我在移动菜单中使用1个过滤器,而在正常菜单中使用1个过滤器时).如下所示:
因此,这两种解决方案都还不是最优的,感谢您对这个谜题的任何帮助!
下面是简化的代码.每当最低价格过滤器更改时,FilterOptions数组只显示符合价格条件的可能产品类别.当这种情况发生时,位置不再对应于正确的值.
Child Component - FilterCheckboxItem.vue个
<template>
<div
v-for="(FilterOption, index) in FilterOptions"
>
<label for="lname">{{FilterOption}}</label>
<input
type="checkbox"
:value="FilterOption"
v-model="modelValue[index]"
/>
</div>
</template>
<script>
export default {
props: {
FilterOptions: {
type: Array,
},
modelValue: {
type: Array,
},
},
}
</script>
Parent Component个
<template>
<FilterCheckboxItem
ref="Category"
name="Category"
:FilterOptions="CategoriesWithinPriceReq"
v-model="FilteredCategories"
/>
<input v-model="MinimalPrice">
</template>
<script>
import FilterCheckboxItem from './Comp.vue'
export default {
components: { FilterCheckboxItem },
data(){
return {
FilteredCategories: [],
CategoryOptions: ["A","B","C"],
MinimalPrice: 5,
Products:
[
{name: 'test1', price: 10, category: "A"},
{name: 'test2', price: 15, category: "B"},
{name: 'test3', price: 20, category: "C"},
{name: 'test4', price: 8, category: "C"}
]
}
},
computed: {
FilteredProducts: function(){
return this.filterProductsByCategory(this.filterProductsByPrice(this.Products))
},
CategoriesWithinPriceReq: function(){
let CategoriesMeetingFilter = this.filterProductsByPrice(this.Products);
let uniqueCatgeoriesMeetingFilters = [
...new Set(CategoriesMeetingFilter.map(({ category }) => category)),
];
return uniqueCatgeoriesMeetingFilters;
},
},
methods: {
filterProductsByPrice: function(products){
return products.filter((product)=>product.price>=this.MinimalPrice)
},
filterProductsByCategory: function(products){
const selected_categories = this.CategoriesWithinPriceReq.filter((category, bool) => this.FilteredCategories[bool])
const results = products.filter((product) => selected_categories.indexOf(product.category) !==-1)
// Only filter if atleast one box is checked, otherwise return all products
return selected_categories && selected_categories.length? results: products
}
}
}
</script>