Vue.js- Vuex更新状态内部数组中的对象,该状态未反映在组件DOM中

问题描述

Vuex /商店:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        todos: [
            {id: 1,text: 'Clean kitchen',done: false},{id: 2,text: 'Clean bedroom',{id: 3,text: 'Clean bathroom',text: 'Clean clothes',done: true},],},mutations: {
        x(state,data) {
            state.todos[0] = data;
        }
    },});

export default store;

Test.vue:

<template>
<div class="container">
    <ul>
        <li
            v-for="(item,i) in todos"
            :key="i"
        >
            <span class="description">{{ item.text }}</span>
            <span class="status">{{ item.status }}</span>
        </li>
    </ul>
    <button @click="x">Change object</button>
</div>

</template>

<script>
import { mapState } from 'vuex';

export default {
    methods: {
        x() {
            this.$store.commit('x',{id: 34,text: 'Celebrate birthday',done: false});
        }
    },computed : {
        ...mapState(['todos']),}
</script>

单击“更改对象”按钮后,我可以在Vue Dev Tools中看到商店的状态已更改,但是组件Test.vue所显示的数据未更改,并且第一个li项“清洁厨房”仍然存在。当我在Vue Dev Tools中提交更改时,就会发生更改。不知道我在做什么错。

状态https://vuex.vuejs.org/guide/state.html “只要store.state.count发生更改,它将导致重新计算计算出的属性,并触发相关的DOM更新。”

解决方法

您有一个enter image description here,因此应使用Vue.set函数:

 x(state,data) {
            Vue.set(state.todos,data);
        }

有关更多详细信息,请检查reactivity caveat