我正在撤销我的Vuejs项目中的Airbnb Eslint (使用Vue-cli)。其中一个规则是不重新分配。为了控制状态(使用Vuex),必须使用突变/操作:
规则冲突
mutations: {
increase: (state) => {
state.counter++;
}
}按规则更改后的
mutations: {
increase: (state) => {
const thisState = state;
thisState.coutner++;
}
}是否有更好的方法来写上面的陈述,而不是打破条条框框?
解决方案(多亏了https://stackoverflow.com/users/3548338/cobaltway的https://stackoverflow.com/a/44658727/6665785)
将'state'添加到规则的ignorePropertyModificationsFor中。
发布于 2017-06-20 16:42:02
不,对不起。
由于Vuex存储的状态是由Vue响应的,所以当我们改变状态时,观察状态的Vue组件将自动更新。这也意味着Vuex突变在与普通Vue一起工作时会受到同样的反应性警告。
来源:https://vuex.vuejs.org/en/mutations.html
这确实意味着必须对参数进行变异才能使任何更改变为实际状态。唯一的解决办法是关闭这条规则。
增编:
我可能有更好的解决办法。请注意,这是他们的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数组中,以便在修改状态属性时不会遇到错误。
发布于 2020-09-04 17:13:18
备选方案:您可以使用Vue.set。
Vue.set使用相同的reactiveSetter函数(参考文献)。
例如:
import Vue from 'vue';
const state = () => ({ counter: 0 });
const mutations = {
increase(states) {
Vue.set(states, 'counter', states.counter + 1);
},
};注意:
发布于 2020-09-07 17:22:20
如果不希望更改Airbnb配置的规则,可以执行以下操作:
mutations: {
increase: (state) => {
const thisState = {...state};
thisState.counter++;
Object.assign(state, thisState);
}
}`在上面,您可以复制现有状态,修改复制状态上的计数器,然后用新更新的状态替换现有状态。
https://stackoverflow.com/questions/44657142
复制相似问题