this.$store.watch
时间: 2023-11-28 18:43:02 浏览: 40
.$store.watch是VueX中的一个API,用于监听VueX store中的数据变化。当store中的数据发生变化时,watch函数会被调用。具体用法如下:
```javascript
this.$store.watch(
(state) => state.count,
(newCount, oldCount) => {
console.log(`new count is ${newCount}, old count is ${oldCount}`)
}
)
```
上述代码中,我们监听了store中的count属性,当count属性发生变化时,watch函数会被调用,并打印出新旧count的值。
相关问题
watch: { '$store.state.crossborderCartList': { handler: function(newVal, oldVal) { this.count = 0; newVal.forEach(data => { data.cartItems.forEach(item => { this.count += item.quantity; }); }); }, deep: true } },让页面一进入就加载计算
这段代码是一个 Vue 组件中的 watch 属性,用于监听 Vuex store 中的 crossborderCartList 对象的变化。一旦 crossborderCartList 对象发生变化,就会触发该函数中的代码,重新计算 count 的值。
如果想要页面一进入就加载计算,可以将该函数提取出来,然后在组件的 created 生命周期钩子函数中调用一次。代码如下:
```
watch: {
'$store.state.crossborderCartList': {
handler: 'updateCount',
deep: true
}
},
created() {
this.updateCount(this.$store.state.crossborderCartList);
},
methods: {
updateCount(newVal, oldVal) {
this.count = 0;
newVal.forEach(data => {
data.cartItems.forEach(item => {
this.count += item.quantity;
});
});
}
}
```
uniapp在data中获取store中的数据
在uniapp中,通过 `this.$store.state` 可以直接获取 Vuex store 中的状态。因此,你可以在组件的 `data` 中直接使用它来初始化组件的状态。
例如,如果你的 Vuex store 中有一个 `userInfo` 状态,你可以这样在组件的 `data` 中使用它:
```javascript
export default {
data() {
return {
username: this.$store.state.userInfo.username,
email: this.$store.state.userInfo.email
}
}
}
```
这样,组件的 `username` 和 `email` 就会被初始化为 `userInfo` 对象中的相应属性。
当然,如果你需要监听 `userInfo` 状态的变化,你还需要使用 `watch` 或者 `computed`。例如,你可以这样使用 `computed`:
```javascript
export default {
computed: {
username() {
return this.$store.state.userInfo.username;
},
email() {
return this.$store.state.userInfo.email;
}
}
}
```
这样,当 `userInfo` 状态发生变化时,`computed` 会自动更新组件的状态。
需要注意的是,在使用 `this.$store.state` 时,你需要确保 Vuex store 已经被正确引入到了当前组件中。如果你在组件中引入了 Vuex store,但仍然无法访问 `this.$store.state`,你需要检查是否正确配置了 Vuex store。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)