乐闻世界logo
搜索文章和话题

How to watch store values from vuex

2个答案

1
2

In Vue, if you want to listen for changes in the values stored in Vuex using watch, you can implement this by combining computed properties with watchers. Vuex state changes are reactive, meaning you can simply return the Vuex state in a computed property and listen for changes to this computed property in the watch option.

Here is a specific example:

Assume you have a Vuex store with a state called count.

javascript
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } } });

You want to listen for changes to the count value in a Vue component. You can do this:

javascript
new Vue({ el: '#app', store, computed: { // Use a computed property to retrieve the Vuex state count() { return this.$store.state.count; } }, watch: { // Use a watcher to listen for changes to the computed property count(newVal, oldVal) { console.log(`count value changed from ${oldVal} to ${newVal}`); // You can perform some actions based on the count value change here } } });

In this example, the computed property count is used to retrieve the current count state from Vuex. Then, in the component's watch option, a count watcher is defined, which triggers when the value of the computed property count changes. This way, whenever the count state is modified via a Vuex mutation, the computed property automatically updates, triggering the callback function in the watcher.

Additionally, if you want to deeply watch for changes in object properties, you can set deep: true in the watch option. However, for most scenarios where you're watching a single value, such as the count in the example above, this is unnecessary.

2024年6月29日 12:07 回复

You should not use component watchers to monitor state changes. Instead, I recommend using getters and mapping them to your components.

javascript
import { mapGetters } from 'vuex' export default { computed: { ...mapGetters({ myState: 'getMyState' }) } }

In your store:

javascript
const getters = { getMyState: state => state.my_state }

You can use this.myState in your component to access the store state, which automatically updates when changes occur.

https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper

2024年6月29日 12:07 回复

你的答案