Vue.js- Vuex 更新数组内的对象,内部状态未反映在组件 DOM 中
·
问题: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', 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;
查看.测试:
<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 开发工具中提交更改时,更改就会发生。不知道我做错了什么。
状态https://vuex.vuejs.org/guide/state.html“每当 store.state.count 发生变化时,都会导致计算属性重新评估,并触发相关的 DOM 更新。”
解答
你有一个反应性警告,所以你应该使用Vue.set函数:
x(state, data) {
Vue.set(state.todos,0,data);
}
有关更多详细信息,请查看这个
更多推荐




所有评论(0)