Vuex Mutations 和 Airbnb eslint

Vuex Mutations and Airbnb eslint

我不唱歌Airbnb Eslint on my Vuejs project (using Vue-cli). And one of the rules is no-param-reassign。为了控制状态(使用 Vuex),必须使用突变/动作:

规则冲突

mutations: {
    increase: (state) => {
        state.counter++;
    }
}

按规则修改后

mutations: {
    increase: (state) => {
        const thisState = state;
        thisState.coutner++;
    }
}

有没有更好的方法来编写上面的语句并且不违反 eslint 规则?

解决方案(感谢Cobaltway's

在规则的 ignorePropertyModificationsFor 中添加 'state'

不,抱歉。

Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue [...]

来源:https://vuex.vuejs.org/en/mutations.html

这确实意味着您必须改变参数才能使您的实际状态发生任何变化。唯一的解决办法是关闭该规则。

附录:

我可能有更好的解决办法。请注意,这是 their ESLint:

强制执行的实际规则
'no-param-reassign': ['error', {
  props: true,
  ignorePropertyModificationsFor: [
    'acc', // for reduce accumulators
    'e', // for e.returnvalue
    'ctx', // for Koa routing
    'req', // for Express requests
    'request', // for Express requests
    'res', // for Express responses
    'response', // for Express responses
    '$scope', // for Angular 1 scopes
  ]
}],

您可以将 'state' 添加到 ignorePropertyModificationsFor 数组,这样您在修改状态属性时就不会遇到错误。

备选方案:您可以使用 Vue.set

Vue.set 使用相同的 reactiveSetter 函数 (Reference)。

例如:

import Vue from 'vue';

const state = () => ({ counter: 0 });

const mutations = {
  increase(states) {
    Vue.set(states, 'counter', states.counter + 1);
  },
};

注:

  • 我故意在函数 increase 上使用变量名 states 而不是 state,因为变量 state 可以在上层范围内定义(就像我上面的例子)。如果不将第一个突变的参数重命名为“states”(或其他名称),它将违反规则 no-shadow.

如果您不想更改 Airbnb 配置规则,您可以执行以下操作:`

mutations: {
    increase: (state) => {
        const thisState = {...state};
        thisState.counter++;
        Object.assign(state, thisState);
    }
}`

在上面,您复制了现有状态,修改复制状态的计数器,然后用新更新的状态替换现有状态。