[英]Vuex Mutations and Airbnb eslint
I am unsing Airbnb Eslint on my Vuejs project (using Vue-cli).我在我的 Vuejs 项目中取消了Airbnb Eslint (使用 Vue-cli)。 And one of the rules isno-param-reassign .
规则之一是no-param-reassign 。 In order to control the state (using Vuex), one must use mutations/ actions:
为了控制状态(使用 Vuex),必须使用突变/动作:
Rules conflict规则冲突
mutations: {
increase: (state) => {
state.counter++;
}
}
After changes according to rules按规则修改后
mutations: {
increase: (state) => {
const thisState = state;
thisState.coutner++;
}
}
Is there a better way to write the statement above and not breaking eslint rules?有没有更好的方法来编写上面的语句而不违反 eslint 规则?
Solution (thanks to Cobaltway 's answer )解决方案(感谢Cobaltway的回答)
Add 'state'
to the ignorePropertyModificationsFor
to the rules.将
'state'
添加到规则的ignorePropertyModificationsFor
中。
No, sorry.不,对不起。
Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically.
由于 Vuex 存储的状态是由 Vue 做出的反应,所以当我们改变状态时,观察状态的 Vue 组件会自动更新。 This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue [...]
这也意味着 Vuex 突变在使用普通 Vue [...]
Source: https://vuex.vuejs.org/en/mutations.html来源: https ://vuex.vuejs.org/en/mutations.html
It does mean that you must mutate the parameter to get any change into your actual state.这确实意味着您必须更改参数才能将任何更改变为您的实际状态。 The only solution there is to turn off that rule.
唯一的解决方案是关闭该规则。
Addendum:附录:
I may have a better solution.我可能有更好的解决方案。 Note that this is the actual rule as enforced by their ESLint :
请注意,这是他们的 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
]
}],
You may add 'state'
to the ignorePropertyModificationsFor
array, so you won't encounter error when modifying your state properties.您可以将
'state'
添加到ignorePropertyModificationsFor
数组中,这样在修改状态属性时就不会遇到错误。
Alternative: you can use Vue.set .替代方案:您可以使用Vue.set 。
Vue.set uses the same reactiveSetter function ( Reference ). Vue.set 使用相同的 reactiveSetter 函数( 参考)。
For example:例如:
import Vue from 'vue';
const state = () => ({ counter: 0 });
const mutations = {
increase(states) {
Vue.set(states, 'counter', states.counter + 1);
},
};
Note:笔记:
If you do not wish to alter the rules of the Airbnb config you can do the following:`如果您不想更改 Airbnb 配置的规则,您可以执行以下操作:`
mutations: {
increase: (state) => {
const thisState = {...state};
thisState.counter++;
Object.assign(state, thisState);
}
}`
In the above, you make a copy of the existing state, modify the counter on that copied state, then replace the existing state with the newly updated state.在上面,您复制现有状态,修改该复制状态的计数器,然后用新更新的状态替换现有状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.