我可以从Vuex商店中的一个突变调用commit [英] Can I call commit from one of mutations in Vuex store

查看:118
本文介绍了我可以从Vuex商店中的一个突变调用commit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 vuex 商店,如下所示:

I have a vuex store, like following:

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_CATEGORIES 来自变异: SET_PRODUCTS ,但这给了我错误:

I want to call mutation: SET_CATEGORIES from mutation: SET_PRODUCTS, But this gives me error:


projectFilter.js:22未捕获(在承诺中)ReferenceError:未定义提交(...)

projectFilter.js:22 Uncaught (in promise) ReferenceError: commit is not defined(…)

这应该是正确的方法。我试过 store.commit this.commit ,但这些也给出了类似的错误。

What should be correct way to do this. I tried store.commit and this.commit, but these also gave similar errors.

推荐答案

当你已经进行了变异时,没有办法提交另一个变异。突变是一种改变状态的同步呼叫。在一个突变中,您将无法提交另一个突变。

When you are already doing a mutation, there is no way to commit another mutation. A mutation is a synchronous call which changes the state. Within one mutation, you will not be able to commit another mutation.

以下是Vuex的API参考: https://vuex.vuejs.org/en/api.html

Here is the API reference for Vuex: https://vuex.vuejs.org/en/api.html

当你可以看到,变异处理程序只接收 state payload ,仅此而已。因此,您将 commit 作为 undefined

As you can see, a mutation handler receives only state and payload, nothing more. Therefore you are getting commit as undefined.

In在上面的情况下,您可以将PRODUCT和CATEGORIES设置为与单个提交相同的变异处理程序的一部分。如果以下代码有效,您可以尝试:

In your case above, you can set the PRODUCT and CATEGORIES as part of the same mutation handler as a single commit. You can try if the following code works:

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

编辑:请参阅以下答案由 Daniel S. Deboer 提供。正确的方法是从单个动作中提交两个突变,如他的回答所述。

Please refer to the answer below, provided by Daniel S. Deboer. The correct method is to commit two mutations from a single action, as described in his answer.

这篇关于我可以从Vuex商店中的一个突变调用commit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆