Vue.js- Vuex updating an object within an array inside state not reflected in component DOM(Vue.js- Vuex 更新数组中的对象,内部状态未反映在组件 DOM 中)
问题描述
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 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Vue.js- Vuex 更新数组中的对象,内部状态未反映在组件 DOM 中
基础教程推荐
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01