vue2组件中监听vuex中state的值

vue2组件中监听Vuex 中state的值可以使用 mapState

官网链接:

mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性。Getter | Vuex (vuejs.org)

参考文档:

使用方法:

1. Vuex 中数据: state:{ message:"" } 

2. 在组件A中导入 mapGetters :import { mapState } from 'vuex' 

3. 在组件A的计算属性中使用对象展开运算符将 getter 混入 computed 对象中:

//  A组件中映射 state数据 到计算属性
    computed: {
        ...mapState(['message'])
    }

4. 在组件A的watch中监听message:

watch: {
    // 监听vuex中的数据
    message(newValue,oldValue) {
        console.log('监听vuex中的message | newValue', newValue);
        console.log("oldValue",oldValue)
    }
}

 

posted @ 2024-05-28 17:22  sunshine233  阅读(267)  评论(0编辑  收藏  举报