我们应该对非计算状态 属性 使用 getters 吗?
Should we use getters for a non-computed state property?
我已经使用 vuex 大约一个星期了。
我的商店中有以下状态
state: {
propA: "test",
propB: 5.9
}
我想在我的组件中访问 propA
。所以我使用以下
this.$store.state.propA;
一切正常
但我观看和遵循的所有教程都建议使用 getter 访问状态 属性,如下所示
getters: {
propA(state){
return state.propA:
}
}
并在组件中使用如下
this.$store.getters.propA;
我是否必须为我想要访问的状态中的每个 属性 设置一个 getter,即使它不是状态 属性 的计算值
为每个 属性 设置 getters 更加冗长,我们可以直接使用 this.$store
访问
不,没有必要为每个 属性 设置 getter。
只有在需要一些额外的计算时才需要 getter。来自 vuex documentation for getters:
Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them
因此,要在组件中访问 属性,只需使用
this.$store.state.propA;
或者,使用 mapState
助手:
对象版本:
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// arrow functions can make the code very succinct!
propA: state => state.propA,
// passing the string value 'propB' is same as `state => state.propB`
propBAlias: 'propB'
})
}
数组版本:
computed: mapState([
// map this.propA to store.state.propA
'propA'
])
我已经使用 vuex 大约一个星期了。 我的商店中有以下状态
state: {
propA: "test",
propB: 5.9
}
我想在我的组件中访问 propA
。所以我使用以下
this.$store.state.propA;
一切正常
但我观看和遵循的所有教程都建议使用 getter 访问状态 属性,如下所示
getters: {
propA(state){
return state.propA:
}
}
并在组件中使用如下
this.$store.getters.propA;
我是否必须为我想要访问的状态中的每个 属性 设置一个 getter,即使它不是状态 属性 的计算值
为每个 属性 设置 getters 更加冗长,我们可以直接使用 this.$store
不,没有必要为每个 属性 设置 getter。
只有在需要一些额外的计算时才需要 getter。来自 vuex documentation for getters:
Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them
因此,要在组件中访问 属性,只需使用
this.$store.state.propA;
或者,使用 mapState
助手:
对象版本:
import { mapState } from 'vuex' export default { // ... computed: mapState({ // arrow functions can make the code very succinct! propA: state => state.propA, // passing the string value 'propB' is same as `state => state.propB` propBAlias: 'propB' }) }
数组版本:
computed: mapState([ // map this.propA to store.state.propA 'propA' ])