Search code examples
vue.jsvuejs2vuex

Vuex: How to replace function emitting between parent and child with Vuex?


I am using Vuex for state right now and taking advantage of getters to acquire state so that I don't have to use props. However, I am curious if I can use Vuex to replace this type of function emitting. How would that be done with Vuex, if it's even possible.

Parent

<child-component @handleselectproduct="selectProduct"></child-component>

selectProduct: function() {
   axios.get()
}

Child

<button @click="selectProduct></button>

selectProduct: function() {
    this.$emit('handleselectproductselection'); 
}

Solution

  • You could use vuex actions and mutations. Mutations are used for synchronous and actions for asynchronous calls. You could imagine them as setters as opposed to getters that you already use. So in your current example, you would call an action which may or may not set a state property through a mutation. you would define this action with:

        const store = new Vuex.Store({
          state: {
            selectedProduct: {}
          },
          getters: {
            getSelectedProduct: state => {
              return state.selectedProduct
            }
          },
          mutations: {
            selectProduct(state, payload) {
              state.selectedProduct = payload
            }
          },
          actions: {
            async selectProduct(context, axios) {
              const { commit } = context
              const product = await axios.get(...) // some call
              commit('selectProduct', product)
            }
          }
        })
    

    After defining these, you can call the action through the this.$store.dispatch('selectProduct', axios) method in the child component and have your result available in the parent component or wherever else you may need it. And if you need some sort of notification that the property has changed (you need to do some change to the selectedProduct data and then show it), you can set a watcher function on the respective getter or just use computed properties that use the getter and they will pick up the change.

    You can find out more about actions at https://vuex.vuejs.org/guide/actions.html