描述(TL; DR):
当我通过v-model
将“对象的对象”从vuex的商店传递给组件时,模型的修改会产生错误。通过“对象对象”时仅。一切都很好。
当我告诉“对象的对象”时,我指的是这种结构:{'A': {name: 'first'}, 'B': {name: 'second'}}
。
工作流程和结构:
view (page)
- > parent
- > child
; Object
并将其传递给组件( - > parrent
- > child
); .sync
”,因此组件不应该改变商店中的对象; child
发生更改后,child
必须将结果返回parent
,parent
返回view
,view
应将结果保存至Error when evaluating setter "value.name": Error: [vuex] Do not mutate vuex store state outside mutation handlers. (found in component: <child>)
vuex的二传手; 错误消息:
getObjFromStore // return {'A': {name: 'first'}, 'B': {name: 'second'}}
Getter(来自商店):
<parent :value="getObjFromStore"></parent>
查看(页面):
<template>
<div v-for="v in value">
<child :value="v"></child>
</div>
</template>
<script>
import Child from 'components/child'
export default {
data () {
return {}
},
props: {
value: {
type: Object
}
},
components: {
Child
}
}
</script>
父组件:
<template>
<input type="text" v-model="value.name">
</template>
<script>
export default {
data () {
return {}
},
props: {
value: {
type: Object
}
}
}
</script>
子组件:
level
P.S。我认为问题的发生是因为对象通过引用传递。但是如何对抗这个错误?
答案 0 :(得分:1)
Take a look at Vuex form handling docs. It encourages using @input
event or v-model
with computed props...
Assuming obj is a computed property that returns an Object from the store, the v-model here will attempt to directly mutate obj.message when the user types in the input. In strict mode, this will result in an error because the mutation is not performed inside an explicit Vuex mutation handler.
答案 1 :(得分:0)
基本上只有2个选项:
props
; @input
事件或v-model
使用计算出道具(例如pkawiak&#39; s回答https://stackoverflow.com/a/39249362/930170); 我更喜欢使用深度显示,而我确定对象不是太大。这种方法有助于保持代码更清洁,更易于维护。
第二种方法仅适用于预期对象血腥大的情况