javascript - 将对象(带有对象)传递给组件时出现 Vuex 突变错误

标签 javascript vue.js vue-component vuex

描述(tl;dr):

当我通过 v-model 将“对象的对象”从 vuex 存储传递到组件时,模型的修改会产生错误。 当“对象的对象”通过时。对于任何其他类型,一切都可以。

当我告诉“对象的对象”时,我指的是这种结构:{'A': {name: 'first'}, 'B': {name: 'second'}}

工作流程和结构:

  • 结构: View (页面) -> 父级 -> 子级
  • View 从存储中获取一个 Object 并将其传递给组件(->parent->child);
  • 不允许“.sync”,因此组件不应改变存储中的对象;
  • child 发生更改后,child 必须将结果返回给 parentparent 返回给 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/

相关文章:

javascript - Jquery 在 Ajax 加载的 Div 上拖放

javascript - 如何使用 Angular.js 根据特定条件加载 Controller

javascript - 正则表达式中的问题

vue.js - Vue预渲染闪烁

javascript - Crockford 关于构造函数调用模式的代码

javascript - 选中下拉列表中的复选框后,如何清除 v-autocomplete(多个)搜索输入?

javascript - 在js文件中使用vuejs mixins

javascript - Vue.js - 滚动到不起作用的元素

javascript - Vuejs : Show confirmation dialog before route change

javascript - 视觉 : wrapper for slots ignoring already-defined slots