filter array in vuex
To filter an array in Vuex using Vue.js, you can follow these steps:
- Import the necessary modules:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
- Create a new Vuex store instance:
const store = new Vuex.Store({
state: {
items: [
{ id: 1, name: 'Item 1', category: 'A' },
{ id: 2, name: 'Item 2', category: 'B' },
{ id: 3, name: 'Item 3', category: 'A' },
// ... other items
]
}
});
- Define a getter to filter the array based on a specific condition:
getters: {
filteredItems: state => category => {
return state.items.filter(item => item.category === category);
}
}
- Use the getter in your Vue component:
computed: {
filteredItems() {
return this.$store.getters.filteredItems('A');
}
}
By following these steps, you can successfully filter an array in Vuex using Vue.js.