将Object(带对象)传递给组件时的Vuex变异错误

时间:2016-08-31 11:53:30

标签: javascript vue.js vue-component vuex

描述(TL; DR):

当我通过v-model将“对象的对象”从vuex的商店传递给组件时,模型的修改会产生错误。通过“对象对象”时。一切都很好。

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

工作流程和结构

  • 结构:view (page) - > parent - > child;
  • 查看从商店获取Object并将其传递给组件( - > parrent - > child);
  • 不允许“.sync”,因此组件不应该改变商店中的对象;
  • child发生更改后,child必须将结果返回parentparent返回viewview应将结果保存至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。我认为问题的发生是因为对象通过引用传递。但是如何对抗这个错误?

2 个答案:

答案 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个选项:

  1. 将对象的深层复制传递给props;
  2. 使用@input事件或v-model使用计算出道具(例如pkawiak&#39; s回答https://stackoverflow.com/a/39249362/930170);
  3. 我更喜欢使用深度显示,而我确定对象不是太大。这种方法有助于保持代码更清洁,更易于维护。

    第二种方法仅适用于预期对象血腥大的情况