【问题标题】:Vuex mapGetters error ''Property or method "isAuthenticated" is not defined''Vuex mapGetters错误''未定义属性或方法“isAuthenticated”''
【发布时间】:2020-06-26 13:41:25
【问题描述】:

在我的组件中,我试图从我的 auth 模块访问 getter。 这是store/auth.js中的getter函数

  getters: {
    isAuthenticated: (state) => !!state.token,
  },

这就是我尝试访问和显示这些数据的方式

  // html in template of component
  <span
    v-if='this.isAuthenticated'
    class='font-weight-bold grey--text text--darken-3'>
    Hello
  </span>

  -------------------

  // computed properties of component
  computed: {
    ...mapGetters([
      'auth/isAuthenticated',
    ]),
  },

在开发工具中,这是我得到的错误 ' 属性或方法“isAuthenticated”未在实例上定义,但在渲染期间被引用。' 我真的不知道为什么也不知道如何访问这些数据,在 Vue 调试器中我可以看到 getter 工作并且返回 true。

我已经尝试过其他方式来访问数据,例如

isAuthenticated: () => this.$store.getters.isAuthenticated // and this.$store.getters.auth.isAuthenticated

但是当我尝试访问模板中的计算函数时,这会给出一个不同的错误typeError: Cannot read property '$store' of undefined

这真的很烦人,因为据我所知,我正在正确地尝试访问商店但它无法正常工作。

非常感谢您的解释。谢谢。

【问题讨论】:

    标签: vue.js vuejs2 vuex vuex-modules


    【解决方案1】:

    您在两种不同的方法中有两个不同的错误。让我们先看看你的第一种方法

    ---
      <span
        v-if='this.isAuthenticated'
    ---
    computed: {
        ...mapGetters([
          'auth/isAuthenticated',
        ]),
      }
    ---
    

    在这里,您的问题是您正在尝试映射命名空间的 getter,但尝试在没有命名空间的情况下访问属性。您可以使用object parameter for the mapGetters function 解决此问题:

    computed: {
        ...mapGetters({
          isAuthenticated: 'auth/isAuthenticated',
        }),
      }
    

    在您的第二种方法中,您几乎做对了,但遇到了一系列不同的问题:

    isAuthenticated: () => this.$store.getters.isAuthenticated
    

    首先,如果模块是命名空间的,那么访问 getter 的正确方法是this.$store.getters['auth/isAuthenticated']

    除此之外,你不应该在 Vue 组件中使用箭头函数,因为 this 上下文丢失了(它指向函数而不是 Vue 实例)。您需要使用常规函数。

    结合这两个修复,结果将是:

    isAuthenticated(){ 
      return this.$store.getters['auth/isAuthenticated']
    }
    

    【讨论】:

    • 谢谢,我还没有看到有人引用这样的命名空间模块。再次阅读 Vuex 模块页面,我看到他们说要访问这样的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2021-03-05
    • 2019-02-14
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    相关资源
    最近更新 更多