如何更新 Vuex 中的状态数组?
How to update a state array in Vuex?
我需要能够添加、删除和编辑条目。到目前为止,我只能添加和删除。
我的问题是:添加使用PUSH,删除使用SPLICE。但是编辑呢?
我正在使用 VUEJS、VUEX 和 JavaScript。
我正在做的事的例子:
<b-button type="submit" @click.prevent="submit()">SAVE</b-button>
methods: {
submit() {
this.$v.edit_category.$touch();
if(this.$v.edit_category.$error) return
this.editCategory()
},
editCategory() {
const category = {
value: this.edit_category.value,
text: this.edit_category.text,
category_active: this.edit_category.category_active,
}
this.$store.commit('saveCategory', category)
},
},
store.js:
actions: {
addCategory({ commit }, payload) {
console.log(payload)
commit('addCategory', payload)
},
saveCategory({ commit }, payload) {
console.log(payload)
commit('saveCategory', payload)
},
deleteCategory({ commit }, payload) {
console.log(payload)
commit('deleteCategory', payload)
}
mutations: {
addCategory(state, category) {
state.categories.push(category)
},
saveCategory(state, payload) {
state.categories.push(payload)
},
deleteCategory(state, category) {
var index = state.categories.findIndex(c => c.value === category.value)
state.categories.splice(index, 1)
},
使用Vue.set
:
import Vue from 'vue';
// ...
editCategory(state, category) {
var index = state.categories.findIndex(c => c.value === category.value);
Vue.set(state.categories, index, category); // ✅ Vue.set
},
这是必需的,因为阅读 docs 我们看到:
Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
我需要能够添加、删除和编辑条目。到目前为止,我只能添加和删除。
我的问题是:添加使用PUSH,删除使用SPLICE。但是编辑呢?
我正在使用 VUEJS、VUEX 和 JavaScript。
我正在做的事的例子:
<b-button type="submit" @click.prevent="submit()">SAVE</b-button>
methods: {
submit() {
this.$v.edit_category.$touch();
if(this.$v.edit_category.$error) return
this.editCategory()
},
editCategory() {
const category = {
value: this.edit_category.value,
text: this.edit_category.text,
category_active: this.edit_category.category_active,
}
this.$store.commit('saveCategory', category)
},
},
store.js:
actions: {
addCategory({ commit }, payload) {
console.log(payload)
commit('addCategory', payload)
},
saveCategory({ commit }, payload) {
console.log(payload)
commit('saveCategory', payload)
},
deleteCategory({ commit }, payload) {
console.log(payload)
commit('deleteCategory', payload)
}
mutations: {
addCategory(state, category) {
state.categories.push(category)
},
saveCategory(state, payload) {
state.categories.push(payload)
},
deleteCategory(state, category) {
var index = state.categories.findIndex(c => c.value === category.value)
state.categories.splice(index, 1)
},
使用Vue.set
:
import Vue from 'vue';
// ...
editCategory(state, category) {
var index = state.categories.findIndex(c => c.value === category.value);
Vue.set(state.categories, index, category); // ✅ Vue.set
},
这是必需的,因为阅读 docs 我们看到:
Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g.
vm.items[indexOfItem] = newValue