直接访问 vuex 状态属性(没有 getter)是不好的做法,为什么?
is it bad practice to access vuex state properties directly (without getters), and why?
如果这是我的 store.js 文件:
const state = {
count: 0,
loggedIn: false
}
const mutations = {
UP_COUNT(state) {
state++;
}
}
const actions = {
upCount({ commit }) {
commit('UP_COUNT');
}
}
假设要从我的一个 Vue 组件增加状态 count
,我将调用一个动作,然后提交一个突变:
this.$store.dispatch('upCount');
那么在另一个 Vue 组件中,我想使用状态计数:
<div class="count">{{ this.$store.state.count }}</div>
这种风格有什么问题? (对比使用 $this.store.getters
...)
正如我在 上指出的那样,您 必须 做事没有硬性规定,但最好遵循实践并坚持下去。
使用 getters 似乎有点过头了,但是只要 getter 名称保持不变,您就可以使用 getters 在幕后更改数据,这样可以节省大量工作重构并试图找到对您可能使用过的其他地方的所有引用 this.$store.state.module.someValue
。
它还允许您 return 基于多个状态变量的数据合并为一个 getter 即
`isAllowed: 'getIsAllowed'`
可以基于
getIsAllowed (state) {
return state.loggedIn && state.hasPermission && state.somethingElse
}
您可以在一处轻松更改 isAllowed
基于的内容,而不是使用组件中的每个状态变量并多次执行逻辑。
如果这是我的 store.js 文件:
const state = {
count: 0,
loggedIn: false
}
const mutations = {
UP_COUNT(state) {
state++;
}
}
const actions = {
upCount({ commit }) {
commit('UP_COUNT');
}
}
假设要从我的一个 Vue 组件增加状态 count
,我将调用一个动作,然后提交一个突变:
this.$store.dispatch('upCount');
那么在另一个 Vue 组件中,我想使用状态计数:
<div class="count">{{ this.$store.state.count }}</div>
这种风格有什么问题? (对比使用 $this.store.getters
...)
正如我在
使用 getters 似乎有点过头了,但是只要 getter 名称保持不变,您就可以使用 getters 在幕后更改数据,这样可以节省大量工作重构并试图找到对您可能使用过的其他地方的所有引用 this.$store.state.module.someValue
。
它还允许您 return 基于多个状态变量的数据合并为一个 getter 即
`isAllowed: 'getIsAllowed'`
可以基于
getIsAllowed (state) {
return state.loggedIn && state.hasPermission && state.somethingElse
}
您可以在一处轻松更改 isAllowed
基于的内容,而不是使用组件中的每个状态变量并多次执行逻辑。