Vue.js-Vuex 更新未反映在组件 DOM 中的状态内部数组中的对象 [英] Vue.js- Vuex updating an object within an array inside state not reflected in component DOM
问题描述
Vuex/商店:
从'vue'导入Vue;从 'vuex' 导入 Vuex;Vue.use(Vuex);const store = new Vuex.Store({状态: {待办事项: [{id: 1, text: 'Clean kitchen', done: false},{id: 2, text: '干净的卧室', done: false},{id: 3, text: '清洁浴室', done: false},{id: 3, text: '干净的衣服', done: true},],},突变:{x(状态,数据){state.todos[0] = 数据;}},});导出默认商店;
Test.vue :
<div class="container"><ul><button @click="x">更改对象</button>
</模板><脚本>从 'vuex' 导入 { mapState };导出默认{方法: {X() {this.$store.commit('x', {id: 34, text: '庆祝生日', done: false});}},计算:{...mapState(['todos']),},}
当按钮更改对象"出现时单击我可以在 Vue Dev Tools 中看到 store 的状态已更改但组件 Test.vue 显示的数据未更改且第一个 li 项Clean kitchen"遗迹.当我在 Vue Dev Tools 中提交更改时,更改就会发生.不知道我做错了什么.
状态 https://vuex.vuejs.org/guide/state.html每当 store.state.count 发生变化时,都会导致计算属性重新评估,并触发相关的 DOM 更新."
你有一个 反应警告,所以你应该使用 Vue.set
函数:
x(state, data) {Vue.set(state.todos,0,data);}
有关详细信息,请查看此
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."
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
这篇关于Vue.js-Vuex 更新未反映在组件 DOM 中的状态内部数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!