Can I call commit from one of mutations in Vuex store

后端 未结 12 1093
醉酒成梦
醉酒成梦 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:22

    To share code between mutations, you must create a new function that performs the work, which you can then reuse. Fortunately, mutations are just plain old functions, and we can pass the state parameter around however we like, so this is quite easy to do.

    For example:

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

提交回复
热议问题