计算数据未在Vue中更新

时间:2019-01-23 09:22:15

标签: vue.js vuex quasar-framework

我正在为我的应用程序使用类星体框架和vuex。父组件正在使用vuex存储中的数据渲染子组件。子组件是可编辑的,如果我按Enter键,商店将更新。但是父组件中的计算属性不会更新。 这是我的代码:

parent-component.vue

<template>
<div>
    <div v-for="(object, objKey) in objects"
         :key="objKey">
        <new-comp
                :is=object.type
                :objId="object.id"
        ></new-comp>
    </div>
</div>
</template>

<script>
import ChildComponent from './child-component';

export default {
    name: 'ParentComponent',
    components: {
        ChildComponent
    },
    computed : {
        objects(){
            return this.$store.state.objects.objects;
        }
    },
    mounted() {
        this.assignEnterKey();
    },
    methods: {
        assignEnterKey() {
            window.addEventListener('keydown',function(e) {
                if(e.which === 13) {
                    e.preventDefault();
                }
            });
        }
    }
}

child-component.vue

<template>
  <div contenteditable="true" @keydown.enter="addChildComp" class="child-container">
    Tell your story
  </div>
</template>
<script>
export default {
    name: 'ChildComponent',
    props: ['objId'],
    data() {
        return {
            id: null
        }
    },
    computed : {
        serial(){
            return this.$store.state.objects.serial;
        }
    },
    methods: {
        addChildComp() {
            let newId = this.objId + 1;
            let newSerial = this.serial + 1;
            this.$store.commit('objects/updateObjs', {id: newId, serial: newSerial});
        }
    }
}

state.js

export default {
 serial: 1,
 objects: {
     1:
       {
       "id" : 1,
       "type" : "ChildComponent",
       "content" : ""
     }
 }
}

mutation.js

export const updateObjs = (state, payload) => {
  let id = payload.id;
  let serial = payload.serial;
  state.objects[serial] = {
    "id" : id ,
    "type" : "ChildComponent",
    "content" : ""
  };
 }

1 个答案:

答案 0 :(得分:1)

Vuex突变follow是Vue.js反应性的一般规则,这意味着Vue.js reactivity traps适用于vuex突变。

为了保持反应性,在向state.objects添加属性时,您应该:

  • 使用特殊的Vue.set方法:

    Vue.set(state.objects, serial, { id, "type" : "ChildComponent", "content" : ""})
    
  • 或者,重新创建state.objects对象而不是对其进行突变:

    state.objects = { ...state.objects, [serial]: { id, "type" : "ChildComponent", "content" : ""} }