在Vuex突变中访问吸气剂

vue.js Vue.js

2020-03-11

在Vuex存储突变中,是否可以访问吸气剂?考虑下面的例子。

new Vuex.Store({
    state: {
        question: 'Is it possible to access getters within a Vuex mutation?'
    },
    mutations: {
        askQuestion(state) {
            // TODO: Get question from getter here
            let question = '';

            if (question) {
                // ...
            }
        }
    },
    getters: {
        getQuestion: (state) => {
            return state.question;
        }
    }
});

当然,该示例并没有多大意义,因为我可以question直接在state突变内的对象访问该属性,但是我希望您能看到我正在尝试做的事情。即,有条件地操纵状态。

在突变内,thisis undefinedstate参数可访问state对象,而不是商店的其余部分。

关于突变的文档没有提及任何有关此操作的信息。

My guess would be that it's not possible, unless I missed something? I guess the alternative would be to either perform this logic outside of the store (resulting in code duplication) or implementing an action that does this, because actions have access to the entire store context. I'm pretty sure that it's a better approach, that is to keep the mutation focused on what it's actually supposed to do; mutate the state. That's probably what I'll end up doing, but I'm just curious if accessing a getter within a mutation is even possible?

第792篇《在Vuex突变中访问吸气剂》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
阿飞Pro 2020.03.11

如果有人在寻找简单的解决方案,@ bbugh在这里写出了一种解决方法,只需使变体和吸气剂都使用相同的功能即可:

function is_product_in_cart (state, product) {
  return state.cart.products.indexOf(product) > -1
}

export default {
  mutations: {
    add_product_to_cart: function (state, product) {
      if (is_product_in_cart(state, product)) {
        return
      }
      state.cart.products.push(product)
    }
  },

  getters: {
    is_product_in_cart: (state) => (product) => is_product_in_cart(state, product)
  }
}
米亚小小神乐 2020.03.11

如果您将存储声明为表达式,则还可以在一个变异中引用Store对象,如下所示:

const Store = new Vuex.Store({
  state: {...},
  getters: {...},
  mutations: {
    myMutation(state, payload) {
      //use the getter
      Store.getters.getter
    }
  }
});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android