[英]Nuxt.js store - update object in store object - throw Error: [vuex] do not mutate vuex store state outside mutation handlers
in my Nuxt.js app my store object is:在我的 Nuxt.js 应用程序中,我的商店对象是:
export const state = () => ({
curEditRP: {
attributes:{
name:"",
spouse: {
type: "", // wife/husband
name: ""
}
}
})
to update the attributes of curEditRP i wrote mutations function that called setCurEditRPAttrState:
为了更新 curEditRP 的属性,我编写了名为
setCurEditRPAttrState:
export const mutations = {
setCurEditRPAttrState(state, payload) {
state.curEditRP.attributes[payload.attr] = payload.value;
},
}
from template i used it:从模板我用它:
this.$store.commit("setCurEditRPAttrState", {
value: value,
attr: attributeName,
});
In a name update it works great But in a spouse update it throws an error Error: [vuex] do not mutate vuex store state outside mutation handlers在名称更新中效果很好但是在配偶更新中它会引发错误错误:[vuex] do not mutate vuex store state outside mutation handlers
examples of values: name (works great):值示例:名称(效果很好):
this.$store.commit("setCurEditRPAttrState", {
value: "Peter",
attr: "name",
});
spouse (throws an error):配偶(抛出错误):
this.$store.commit("setCurEditRPAttrState", {
value: { type:"wife",name:"S" },
attr: "spouse",
});
clarification: value
is v-model
variable澄清:
value
是v-model
变量
Bs"d, I find the solution. Bs"d,我找到了解决方案。
in update object or array of object i need itarate over object properties and update each one individually在更新对象或对象数组中,我需要遍历对象属性并单独更新每个对象
setCurEditRPAttrState(state, payload) {
if(typeof(payload.value) == 'object') {
let stateAttribute = state.curEditRP.attributes[payload.attr];
if(Array.isArray(payload.value)) {
let stateArrLen = stateAttribute.length;
let valuelen = payload.value.length;
while(stateArrLen > valuelen) {
stateAttribute.pop();
stateArrLen --;
}
for (let index = 0; index < payload.value.length; index++) {
const element = payload.value[index];
if(stateAttribute.length < index + 1) stateAttribute.push({});
Object.keys(element).forEach( key => {
Vue.set(stateAttribute[index], key, element[key])
})
}
}
else {
Object.keys(payload.value).forEach( key => {
Vue.set(stateAttribute, key, payload.value[key])
})
}
}
else {
state.curEditRP.attributes[payload.attr] = payload.value;
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.