Javascript 如何在Vuex中更新状态数组?
我需要能够添加,删除和编辑条目。到目前为止,我只能添加和删除 我的问题是:要添加,请使用“推”,要删除,请使用“拼接”。但是编辑呢 我正在使用VUEJS、VUEX和JavaScript 我正在做的示例:Javascript 如何在Vuex中更新状态数组?,javascript,arrays,vue.js,vuejs2,vuex,Javascript,Arrays,Vue.js,Vuejs2,Vuex,我需要能够添加,删除和编辑条目。到目前为止,我只能添加和删除 我的问题是:要添加,请使用“推”,要删除,请使用“拼接”。但是编辑呢 我正在使用VUEJS、VUEX和JavaScript 我正在做的示例: <b-button type="submit" @click.prevent="submit()">SAVE</b-button> methods: { submit() { this.$v.edit_ca
<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)
},
},
使用:
从“Vue”导入Vue;
// ...
编辑类别(状态,类别){
var索引=state.categories.findIndex(c=>c.value==category.value);
Vue.set(state.categories、index、category);//✅ Vue.set
},
这是必要的,因为阅读以下内容:
Vue无法检测阵列的以下更改:
直接使用索引设置项目时,例如vm.items[indexOfItem]=newValue
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)
},