我已经使用 vuex 大约一周了。 我的商店有以下状态
state: {
propA: "test",
propB: 5.9
}
我想访问我的组件中的propA
。所以我使用以下内容
this.$store.state.propA;
一切正常
但是我观看和遵循的所有教程都建议使用 getter 来访问状态属性,如下所示
getters: {
propA(state){
return state.propA:
}
}
并在组件中使用它,如下所示
this.$store.getters.propA;
我是否必须为我想要访问的状态中的每个属性设置一个 getter,即使它不是状态属性的计算值
为每个属性设置 getter 会比较冗长,我们可以使用 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' ])
关于vue.js - 我们应该对非计算状态属性使用 getter 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48384597/