使用 watch 监听 vuex中数组的变化

2,030 阅读1分钟

可以监听到:

arr.push()

arr.splice()

监听不到:

索引直接设置一个项时, arr[1] = 5

方法一:

使用 arr.push()arr.splice() 等数组方法来修改数组

比如:

// 修改

let oldMenuList = this.$store.getters.get_menu_info;

let pathIndex = pathArr.indexOf(path);

let editItem = oldMenuList[pathIndex];

editItem.active = true;

oldMenuList.splice(pathIndex, 1, editItem);

this.$store.commit('set_menu_list', oldMenuList);
// 赋值

let selectItem = {
    title,
    path,
    active: true,
};

let oldMenuList = this.$store.getters.get_menu_info;

oldMenuList.push(selectItem);

this.$store.commit('set_menu_list', oldMenuList);
// 监听

'$store.getters.get_menu_info': function (newVal) {
    console.log(newVal)
},

方法二:

将数组转成字符串之后监听 JSON.parse(JSON.stringify(arr)),使用的时候在转成数组,修改的时候转成字符串;