【问题标题】:Computed data not updating in Vue计算数据未在 Vue 中更新
【发布时间】:2019-06-16 20:13:07
【问题描述】:

我正在为我的应用程序使用 quasar 框架和 vuex。父组件正在使用来自 vuex 存储的数据渲染子组件。子组件是可内容编辑的,如果我在其上按 Enter 键,则商店会更新。但是父组件中的计算属性没有更新。 这是我的代码:

父组件.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" : ""
  };
 }

【问题讨论】:

    标签: vue.js vuex quasar-framework


    【解决方案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" : ""} }
      

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2021-11-05
      相关资源
      最近更新 更多