Can I call commit from one of mutations in Vuex store

后端 未结 12 1071
醉酒成梦
醉酒成梦 2021-02-03 16:25

I have a vuex store, like following:

import spreeApi from \'../../gateways/spree-api\'
// initial state
const state = {
  products: [],
  categories: []
}

// mu         


        
12条回答
  •  再見小時候
    2021-02-03 17:25

    Edit : I stumbled upon a very similar problem and the solution for me was to use a vuex getter : https://vuex.vuejs.org/en/getters.html
    Your categories is actually a "computed" version of your products. Having categories as a getter allows you to keep them in sync with products and avoids duplicating the data in your store.

    For the sake of answering the question in the title i leave my original answer.
    An alternative to Daniel Buckmaster solution :

    const mutations = {
     SET_PRODUCTS: (state, response) => {
       state.products = response.data.products
       this.SET_CATEGORIES(state)
     },
     SET_CATEGORIES: (state) => {
       state.categories = state.products.map(product => product.category)
     }
    }
    

    As you can see you could directly call the mutation itself. (as Daniel said, they are just plain functions after all)
    I believe that this is a more appropriate answer to the original question : it is an actual way of composing mutations without code duplication or extra functions

提交回复
热议问题