Vue.js- Vuex updating an object within an array inside state not reflected in component DOM

给你一囗甜甜゛ 提交于 2020-11-25 03:27:09

问题


Vuex/store :

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', done: false},
            {id: 3, text: 'Clean bathroom', done: false},
            {id: 3, 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>

When the button "Change object" is clicked I can see in Vue Dev Tools the state of the store has changed but the data displayed by the component Test.vue has not changed and the first li item "Clean kitchen" remains. When I commit the changes in Vue Dev Tools the change happens. Not sure what I am doing wrong.

States https://vuex.vuejs.org/guide/state.html "Whenever store.state.count changes, it will cause the computed property to re-evaluate, and trigger associated DOM updates."


回答1:


You have a reactivity caveat, so you should use Vue.set function :

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

For more details check this



来源:https://stackoverflow.com/questions/63404747/vue-js-vuex-updating-an-object-within-an-array-inside-state-not-reflected-in-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!