Vuex中更新对象或数组的值,视图不更新的问题

造成原因

Vue不能监听到数组或对象值的改变

出现场景

1、利用索引直接设置一个项时,例如: vm.items[indexOfItem] = newValue
2、修改数组的长度时,例如: vm.items.length = newLength
3、直接给对象赋值新属性,例如: vm.items.newKey = newValue

解决方式

Vue.set(target, key, value)

Vuex 中 store 的代码

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        testObj: {}, // 聊天信息
        testArr: [6,5,4]
    },
    mutations: {
        setChatList(state, result){
            // state.testObj.name = '张三'; // 错误 - 只会更新数据,不会更新视图
            Vue.set(state.testObj,'name','张三') // 正确

            // state.testArr[2] = 123; // 错误 - 只会更新数据,不会更新视图
            Vue.set(state.testArr,2,123) // 正确
        }
    },
    actions: {
        updateChatList(context, result){ // 更新聊天信息
            context.commit('setChatList', result);
        }
    }
})

组件中的代码

<template>
    <div id="app">
        code
    </div>
</template>

<script>
    export default {
        name: "app",
        data() {
            return {

            }
        },
        sockets: {
            connect(e) {
                console.log("连接socket:", e);
            },
            disconnect(e) {
                console.log("断开socket:", e);
            },
            reconnect(e) {
                console.log("重连socket:", e);
            },
            chatReceive(e) { // 接收消息:socket发送过来的数据 是个Object
                this.$store.dispatch("updateChatList", e);
            }
        },
        mounted() {
            // ...
        }
    }
</script>

猜你喜欢

发表评论

最新发布