描述(tl;dr):
当我通过 v-model 将“对象的对象”从 vuex 存储传递到组件时,模型的修改会产生错误。 仅当“对象的对象”通过时。对于任何其他类型,一切都可以。
当我告诉“对象的对象”时,我指的是这种结构:{'A': {name: 'first'}, 'B': {name: 'second'}}
。
工作流程和结构:
- 结构:
View (页面)
->父级
->子级
; - View 从存储中获取一个
Object
并将其传递给组件(->parent
->child
); - 不允许“
.sync
”,因此组件不应改变存储中的对象; child
发生更改后,child
必须将结果返回给parent
,parent
返回给view
,并且view
应该通过 vuex 的 setter 保存它;
错误消息:
Error when evaluating setter "value.name": Error: [vuex] Do not mutate vuex store state outside mutation handlers. (found in component: <child>)
Getter(来自商店):
getObjFromStore // return {'A': {name: 'first'}, 'B': {name: 'second'}}
查看(页面):
<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>
P.S. 我认为问题的发生是因为对象通过引用传递。但如何解决这个错误呢?
最佳答案
看看Vuex form handling文档。它鼓励使用 @input
事件或 v-model
以及计算的 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.
关于javascript - 将对象(带有对象)传递给组件时出现 Vuex 突变错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39248955/