Search code examples
vue.jsvuejs2vuex

Vuex watch all object subproperties


I am watching a Vuex object's individual properties like so:

this.$store.watch( function(state) {return state.views.height}, function() { //do something } )
this.$store.watch( function(state) {return state.views.width}, function() { //do something } )

Is it possible to watch all of the object properties of state.views without specifying the individual properties?


Solution

  • Vuex's watch method takes the same options argument from Vue's $watch method. There's a deep option that allows you to watch all changes to subproperties.

    store.watch(
      state => state.views,
      views => console.log('change', views.height, views.width),
      { deep: true } // <-- options
    )
    

    demo