在这一点上,我陷入了困境:导出过滤器功能并在vuex存储中使用它。到这里没问题。现在,我尝试将@click
事件放到div上。例如,当我单击时。奥迪,过滤器需要仅显示“ audi”,如果我再次单击“ audi”,则需要将其从过滤器中删除。
这是沙箱:https://codesandbox.io/s/filtering-bzphi
filter.js
export const carFilter = car => allcars => {
if (car.length > 0) {
if (allcars.name.includes(car)) {
return true;
} else {
return false;
}
} else {
return true;
}
};
商店
export const store = new Vuex.Store({
state: {
cars: [
{ name: "AUDI" },
{ name: "BMW" },
{ name: "MERCEDES" },
{ name: "HONDA" },
{ name: "TOYOTA" }
],
carBrand: []
},
mutations: {
updateCarsFilter(state, carBrand) {
state.carBrand = carBrand;
}
},
getters: {
filteredCars: state => {
return state.cars.filter(carFilter(state.carBrand));
}
}
});
和 App.js
<template>
<div id="app">
<div class="boxes" :key="index" v-for="(item, index) in cars">{{item.name}}</div>
<List/>
</div>
</template>
<script>
import List from "./List.vue";
export default {
name: "App",
components: {
List
},
computed: {
selectBrand: {
set(val) {
this.$store.commit("updateCarsFilter", val);
},
get() {
return this.$store.state.carBrand;
}
},
cars() {
return this.$store.getters.filteredCars;
}
}
};
</script>
我还为此创建了一个沙箱。您可以检查一下以更好地理解。 https://codesandbox.io/s/filtering-bzphi
答案 0 :(得分:0)
在 store.js
clearFilter
isActiveFilter
更新
carBrand
selectedCars
取代,它是一个数组carBrand
的变异addCarSelection
removeCarSelection
filteredCars
如果包含汽车,则返回selectedCars数组,否则返回cars
状态isSelectedCar
,以检查选择中是否有汽车 carFilter
函数。
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
cars: [
{ name: "AUDI" },
{ name: "BMW" },
{ name: "MERCEDES" },
{ name: "HONDA" },
{ name: "TOYOTA" }
],
selectedCars: []
},
mutations: {
addCarSelection(state, car) {
state.selectedCars.push(car);
},
removeCarSelection(state, car) {
state.selectedCars = state.selectedCars.filter(r => r.name !== car.name);
}
},
getters: {
filteredCars: state => {
if (state.selectedCars.length !== 0) {
// There's selected cars, return filtered
return state.selectedCars;
} else {
return state.cars;
}
},
isSelectedCar: state => car => {
return state.selectedCars.some(r => r.name === car.name);
}
}
});
在 App.vue
中filterCars
(从计算属性searchText
中移出)clearFilter
更新
filterCars
和'clearFilter'方法并映射了商店中的新变异和获取方法 methods: {
addCarSelection(car) {
this.$store.commit("addCarSelection", car);
},
removeCarSelection(car) {
this.$store.commit("removeCarSelection", car);
},
isSelectedCar(car) {
return this.$store.getters.isSelectedCar(car)
},
}
isFilterActive()
计算属性更新
isFilterActive()
和searchText
computed: {
cars() {
return this.$store.getters.filteredCars;
},
},
更新
isSelectedCar
在添加或删除功能之间切换,框始终显示可用的汽车。
列表显示了选定的汽车(如果有的话),否则会显示完整的汽车目录。
<template>
<div id="app">
<div class="boxes" :key="index" v-for="(item, index) in cars">
<div
v-if="!isSelectedCar(item)"
style="cursor:pointer"
@click="addCarSelection(item)"
>{{item.name}}</div>
<div v-else style="cursor:pointer;" @click="removeCarSelection(item)">
{{item.name}}
<small>[x]</small>
</div>
</div>
<List/>
</div>
</template>
该沙箱中提供了更新版本