Search code examples
vue.jsvue-componentvuex

Vuex: How to update component data or call component methods from Store


If I have a store:

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    foo: bar
  },
  mutations: {
    updateComponent (state) {
      // computation and logic
      // update state
      this.$refs.myComponent.updateComponent(state.foo)
    }
  }
}

And I have a component with ref 'myComponent':

<template>
  ...
</template>
<script>
  export default {
    ...
    methods: {
      updateComponent(payload) {
        // do stuff
      }
    }
  }
</script>

I would like to call the 'updateComponent()' method from the store. I can use this.$refs.myComponent from other views and components, but it doesn't work from the Store. I get error TypeError: Cannot read property 'myComponent' of undefined.

Clearly this is not the correct scope for the this.$refs.myComponent when using from the Store.

Can I call updateComponent() from my store mutation, and how?


Solution

  • You could use vuex's subscribe method. Subscribe your component in it's mounted phase:

    mounted() {
        this.$store.subscribe((mutation, state) => {
            switch(mutation.type) {
              case 'updateComponent':
                // Update your component with new state data
              break;
            } 
         })
      }
    

    Reference: https://vuex.vuejs.org/api/#subscribe