store.subscribe
listens to mutators. For example, if you invoke
this.$store.commit('myMutator', payload)
, your subscriber function will be triggered with
myMutator
and
payload
. However, this may not always be the desired behavior.
store.watch
allows you to monitor a specific part of the state that you define, but one downside is that you have to manually stop watching. You could utilize it as shown below:
const unWatchFn = store.watch(
(state) => state.rgbColors.red,
(newRed) => {
console.log(newRed)
}
);
// At some point later
unWatchFn()
In Vue, it's generally advised to avoid using watchers directly because computed properties automatically maintain the calculated values up-to-date. If you must employ watchers, make sure to use them on actual components to prevent memory leaks or unexpected errors. In any case, you will need a getter in your store module. Then, create either a computed property or a watcher in your component based on this getter.
// store.js
export default {
state: {
rgbColors: {
red: 0,
green: 0,
blue: 0
}
},
getters: {
color(state) {
return state.rgbColors;
}
},
mutations: {
setColor(state, { red, green, blue }) {
state.rgbColors.red = red;
state.rgbColors.green = green;
state.rgbColors.blue = blue;
}
}
};
// SomeComponent.vue
<script>
import { mapGetters } from "vuex";
export default {
name: "App",
computed: {
...mapGetters(["color"]),
styling() {
const { red, green, blue } = this.color;
return {
"background-color": `rgb(${red}, ${green}, ${blue})`
};
}
},
watch: {
color: {
deep: true,
handler(newColor) {
console.log("Oh, look, a new color!", newColor);
}
}
},
methods: {
setColor(red, green, blue) {
this.$store.commit("setColor", {
red,
green,
blue
});
}
}
};
</script>
https://codesandbox.io/s/z3m6x5or1l