vue2组件中监听vuex中state的值
约 275 字小于 1 分钟
2025-08-01
vue2
组件中监听 Vuex
中 state
的值可以使用 mapState
。
官网链接
- mapState 辅助函数帮助我们生成计算属性. State|Vuex
- mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性。Getter | Vuex (vuejs.org)
mapState 使用方法
Vuex 中数据:
state:{ message:"" }
在组件 A 中导入
mapState
:import { mapState } from 'vuex'
在组件 A 的计算属性中使用对象展开运算符将
state
的值 混入computed
对象中:// A组件中映射 state数据 到计算属性 computed: { ...mapState(['message']) }
在组件 A 的
watch
中监听message
watch: { // 监听vuex中的数据 message(newValue,oldValue) { console.log('监听vuex中的message | newValue', newValue); console.log("oldValue",oldValue) } }