vuex 中 getters 如何监控对象数组中某一对象的变化?

const state = {
    xxx: [
        {
            active: true
        },
        {
            active: true
        },
        {
            active: false
        }
    ]
}

const getters = {
    activeCount: state => {
        let xxx = state.xxx
        let count = 0
        for(let index in xxx){
            if(xxx[index].active) count++
        }
        return count
    }
}

如上,试图用 Vuex 中的 getters 实现对某一 state 中 active 个数的获取。但这里的 getters 似乎不能像 watch 一样使用类似 deep:true 的方式检测子元素变化。即当 xxx 变化时,activeCount 并没有变。

请问有什么办法能实现这一需求吗?

阅读 7k
2 个回答

这种自动获取active为true数目的需求,建议不要放在vuex中计算,应该在具体的页面去watch。

[...xxx] 展开运算符 了解一下
直接替换

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题