Can I call commit from one of mutations in Vuex store

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

    import spreeApi from '../../gateways/spree-api'
    // initial state
    const state = {
      products: [],
      categories: []
    }
    
    // mutations
    const mutations = {
     SET_PRODUCTS: (state, {response,commit}) => { // here you destructure the object passed to the mutation to get the response and also the commit function
       state.products = response.data.products
       commit('SET_CATEGORIES') // now the commit function is available
     },
     SET_CATEGORIES: (state) => {
       state.categories = state.products.map(function(product) { return product.category})
     }
    
    }
    
    const actions = {
     FETCH_PRODUCTS: ({commit}, filters) => { // here you destructure the state to get the commit function
       return spreeApi.get('products').then(response => commit('SET_PRODUCTS', {response,commit})) // here you pass the commit function through an object to 'SET_PRODUCTS' mutation
     }
    }
    
    export default {
      state,
      mutations,
      actions
    }
    

    This should fix it. You can inject the commit into your mutation from the action so you can commit from your mutation. Hope this helps

提交回复
热议问题