vue.js - 我们应该对非计算状态属性使用 getter 吗?

标签 vue.js vuejs2 vuex

我已经使用 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/

相关文章:

javascript - Vue md-input with Vuex 仅在一个方向上更新

javascript - 无法更新 Vuex 存储和检索数组

javascript - 使用 Vue 和复选框过滤列表?

javascript - 检查多个选项并在 vuex 中进行过滤

javascript - 如何在组件渲染之前在 vuex 中填充商店

javascript - 是否有一个 created() 用于自动调度 vuex Action

javascript - 获取json数据时如何去掉promise

javascript - 在 Vue.js 中单击按钮时清除文本字段?

vue.js - Vue - 更新 Bootstrap 表自定义组件上的数据

javascript - 自定义 Prop 类型 Vue.js