Vue: watch a store object/array property

A few days ago using Vuex I tried to use watcher vue’s property to apply some changes in a specific vue’s component according to a store property. It looks easy to do, just adding to my component:

watch: {
    '$store.state.myStore.aProperty': function(newValue) {
        // do something
    }
}


If this.$store.state.myStore.aProperty it is not an object or array it should work perfectly. But in my case I would like to watch an array of objects. So this solution would not work, that’s because we should use deep property it’s something like:

watch: {
'$store.state.myStore.aProperty': {
deep: true,
handler(newValue): {
// do something
}
}
}

To my surprise this doesn’t work either, looking on internet (including in my favorite lifeguard: StackOverflow), I couldn’t find the solution easly. In fact I had to think about the issue and find my solution on my own, that’s because I’m writting it. Let’s see how looks my store and what’s the change I’m interested to watch:

let myStore = {
    aProperty: {}
};
export default {
    state: myStore,
    mutations: {
        setAProperty: (state, newValue) => {
          state.aProperty[newValue.key]= [];  
          state.aProperty[newValue.key].push(newValue.value)
        }
    }
}

I’m using a new key for my store object and as a value an array where I’m using the push method to add a new value.

Looks like push doesn’t dispatch the correct event to watch vue’s feature. But if I use assign values it works, it’s like: state.aProperty = otherObject it works. So I use a auxiliar variable to save a copy of the current store and re-assign it to the store object in order to dispatch the correct event for watch feature:

let myStore = {
    aProperty: {}
};
export default {
    state: myStore,
    mutations: {
        setAProperty: (state, newValue) => {
            let auxVar = Object.assign({}, state.aProperty);
            auxVar[newValue] = [];
            auxVar[newValue].push(newValue.value); // Using push in auxiliar var
            state.aProperty = auxVar; // This line will dispatch the correct event
        }
    }
}

I hope this is useful to you!


And now as usually let’s learn something interesting on music. Spinetta-Jade was a jazz / rock progressive Argentine band, with incredible exploration between Tango/Symphony rock/Jazz with high virtuosity in fretless bass (by Pedro Aznar), guitar (by Luis A. Spinetta) and other incredible musicians. I love this because it represents the exploration of popular 80’s Argentine rockers in Progressive rock and jazz, since in USA and England this stage was on the 70’s, in this case we add folk, tango and other influences that makes it a precious jewel in the Argentine culture.

 
Ricardo Aragón

Ricardo Aragón

Lead Developer at Pressbooks iam@ricardoaragon.com