VUE 监听 $store 的变化
main.js(或其他入口文件)
import { createApp } from 'vue'
import App from './App.vue'
import store from './store/index' // 导入 store 模块
const app = createApp(App)
app.use(store) // 将 store 注入到应用程序中
app.mount('#app')
组件内部
// YourComponent.vue
export default {
mounted() {
this.$store.subscribe((mutation, state) => {
console.log('$store 发生了变化', mutation, state);
// 这里可以根据需求进行相关操作
})
},
}
我们在组件的
mounted钩子函数中调用了this.$store.subscribe()方法,该方法接收两个参数:第一个参数为回调函数,第二个参数为初始状态。每次$store发生变化时,都会触发回调函数,并将最新的状态作为参数传入。