Observe Vue.js store boolean change inside component

Asked By: Anonymous

I have a vue.js store that holds a boolean value and I need to detect when this changes inside a component. When userEnabled changes I need to call a method inside the component. I don’t need to compute a new value.

My question is should I be using ‘watch’ for this or is there a more efficient way? If so, should I be configuring the watch inside ‘mounted’ and what about unwatch?


import Vue from 'vue';
import Vuex from 'vuex';


export const store = new Vuex.Store({
    state : {
        userEnabled: false,


        <div id="user"></div>
    export default {
        watch: {
            'this.$store.userEnabled': function() {
        mounted: function() {
            this.$store.watch( state => state.userEnabled, (newValue, oldValue) => {
                // call function!


Answered By: Anonymous

If the functionality is to be executed only inside the component, watch is the way to go. You might map userEnabled to a computed prop of the component to improve readability, but that’s optional.

Manually calling $store.watch in mounted mainly gives you the option to store the returned unwatch function and stop watching the property at an arbitrary point. However, if you want to watch the property as long as the component exists anyway, this adds no benefits.

Finally, if the desired functionality should be run whenever userEnabled is changed, regardless of specific components handling the change, a better approach might be to move that code into the Vuex mutation function which changes the value of userEnabled in the store.

techinplanet staff

techinplanet staff

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno