【问题标题】:Vue: how to use a mapState in a computed property?Vue:如何在计算属性中使用 mapState?
【发布时间】:2022-01-14 18:47:09
【问题描述】:

我正在尝试使用 mapState 并拥有该状态,然后使用其下方的计算属性。

 computed: {
    ...mapState(['features']),

    shouldShowExtras(): boolean {
      if (this.features.hasVIP) {
        return true;
      }
      return false;
    },
  }

我无法查明问题,但我的所有测试现在都返回 TypeError: Cannot read properties of undefined (reading 'state')

在我逐个测试之前,就在另一个计算属性中使用映射状态而言,用法是否正确?

【问题讨论】:

  • 这对我来说是正确的。你确定这是导致错误的代码吗?
  • state 在某处未定义很可能意味着商店未正确连接并且在此组件中不可用。

标签: vue.js vuejs2


【解决方案1】:

根据我找到的this 文章,您的语法应该没问题。 (这有助于了解到底发生了什么。)

我猜,您可以在状态为“未定义”的应用程序中找到“state.properties”/“this.$state.properties”,因此无法评估/找到属性变量。

【讨论】:

    【解决方案2】:

    为什么不在 vuex 创建 getter 并调用 getter 而不是 state?

    getters:{
     features: (state) => state.features
    }
    
     computed: {
        ...mapGtters(['features']),
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 2019-11-22
      • 2021-01-31
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多