101

次のようなvuexストアがあります。

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

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

}

const actions = {
 FETCH_PRODUCTS: (state, filters) => {
   return spreeApi.get('products').then(response => state.commit('SET_PRODUCTS', response))
 }
}

export default {
  state,
  mutations,
  actions
}

SET_CATEGORIESMutation:から Mutation:を呼び出したいのですがSET_PRODUCTS、これによりエラーが発生します:

projectFilter.js:22 Uncaught (in promise) ReferenceError: コミットが定義されていません(…)

これを行う正しい方法は何ですか。store.commitとを試しthis.commitましたが、これらも同様のエラーを出しました。

4

15 に答える 15

105

記録のために。ミューテーション メソッドから他のミューテーションを呼び出すには、次のようにします。

const mutations = {
    mutationOne(state, payload){
        this.commit("mutationTwo", payload)
    },
    mutationTwo(state, payload){
        console.log("called from another mutation", payload)
    }
}
于 2019-02-22T15:35:04.817 に答える
15

また、複数のミューテーション間の状態に影響を与える共通コードがある場合、すべてのミューテーションで同じコードを複製する必要がありますか? または、それを行うより良い方法はありますか?

于 2016-12-05T20:39:41.693 に答える
1

おもう

状態とコンポーネントのデバッグが難しいため、別のミューテーションからミューテーションを呼び出すことはお勧めできません

const mutations = {
    mutationOne(state, payload){
        this.commit("mutationTwo", payload)
    },
    mutationTwo(state, payload){
        console.log("called from another mutation", payload)
    }
}

ただし、単純な関数を記述でき、関数は再利用可能です

function mysecondfn(state,payload){
{
// do your stuff here
}


const mutations = {
    mutationOne(state, payload){
mysecondfn(state,payload)
     },

}
于 2020-07-15T15:09:57.287 に答える
0
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
}

これで修正されるはずです。ミューテーションからコミットできるように、アクションからミューテーションにコミットを挿入できます。お役に立てれば

于 2019-02-19T15:46:05.917 に答える
0

Use this

  this.commit('SET_CATEGORIES')
于 2022-02-24T07:41:03.710 に答える