vuex3中的watch不可用
时间: 2024-04-01 15:10:54 浏览: 17
在 Vuex 3 中,`watch` 不再被用作监听 Vuex store 中 state 的变化,而是被用于监听 Vue 组件实例中的属性变化。如果你想监听 Vuex store 中 state 的变化,应该使用 `subscribe` 方法,它允许你在 store 中注册一个回调函数,在每次 mutation 完成后被调用。举个例子:
```javascript
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
store.subscribe((mutation, state) => {
console.log('mutation type: ' + mutation.type)
console.log('new state: ' + JSON.stringify(state))
})
```
上面代码中,我们在 store 中注册了一个回调函数,这个函数会在每次 mutation 完成后被调用,我们可以在这个回调函数中获取 mutation 的类型和最新的 state。这样就可以实现监听 Vuex store 中 state 的变化了。
相关问题
vuex3中的watch
在 Vuex3 中,watch 是一个用于监听 state 中数据变化的方法。watch 方法接收两个参数,第一个参数是要监听的 state 属性,第二个参数是回调函数,当 state 中被监听的属性发生变化时,回调函数将被调用。
例如,我们可以监听 state 中的 count 属性:
```
import { watch } from 'vuex';
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
});
watch(
() => store.state.count,
(newCount, oldCount) => {
console.log(`count changed from ${oldCount} to ${newCount}`);
}
);
```
这段代码会在 state 中的 count 属性发生变化时输出变化前后的值。需要注意的是,watch 方法只能监听 state 中的数据变化,而不能监听 getters 或 actions 中的变化。如果需要监听 getters 或 actions 中的变化,可以使用 computed 属性或者在回调函数中手动获取相应的值。
vuex中的watch
在 Vuex 中,可以使用 watch 来监听 state 中的变化。与 Vue 组件中的 watch 不同,Vuex 中的 watch 可以直接监听 state 中的变化,而不需要在组件中显式地引用 state。
可以使用 store.watch 方法来创建一个 watcher,这个 watcher 会在 state 中的指定属性发生变化时被调用。watch 方法接收两个参数:第一个参数是要监听的 state 属性的名称,第二个参数是一个回调函数,用来处理这个属性发生变化时的操作。
示例代码如下:
```
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
watch: {
count(newValue, oldValue) {
console.log(`count changed from ${oldValue} to ${newValue}`)
}
}
})
store.commit('increment') // count changed from 0 to 1
```
在上面的示例代码中,我们使用 watch 监听了 state 中的 count 属性,当 count 属性发生变化时,会调用回调函数,并输出变化前后的值。我们通过 store.commit('increment') 来手动触发 count 的变化,从而测试 watch 的效果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)