Vuex mapGetters 错误''Property or method "isAuthenticated" is not defined''
Vuex mapGetters error ''Property or method "isAuthenticated" is not defined''
在我的组件中,我试图从我的身份验证模块访问 getters。
这是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',
]),
},
在 devtools 中这是我得到的错误
' 属性 或方法“isAuthenticated”未在实例上定义,但在渲染期间被引用。
我真的不确定为什么也不确定如何访问这些数据,在 Vue 调试器中我可以看到 getter 有效并且正在返回 true。
我已经尝试过其他方法来访问数据,例如
isAuthenticated: () => this.$store.getters.isAuthenticated // and this.$store.getters.auth.isAuthenticated
但是当我尝试访问模板中的计算函数时,这给出了一个不同的错误 typeError: Cannot read property '$store' of undefined
。
这真的很烦人,因为据我所知,我正在正确地尝试访问商店,但它不起作用。
如有解释,将不胜感激。谢谢。
你的两种不同的方法有两个不同的错误。让我们先看看你的第一种方法:
---
<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']
}
在我的组件中,我试图从我的身份验证模块访问 getters。
这是store/auth.js
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',
]),
},
在 devtools 中这是我得到的错误 ' 属性 或方法“isAuthenticated”未在实例上定义,但在渲染期间被引用。 我真的不确定为什么也不确定如何访问这些数据,在 Vue 调试器中我可以看到 getter 有效并且正在返回 true。
我已经尝试过其他方法来访问数据,例如
isAuthenticated: () => this.$store.getters.isAuthenticated // and this.$store.getters.auth.isAuthenticated
但是当我尝试访问模板中的计算函数时,这给出了一个不同的错误 typeError: Cannot read property '$store' of undefined
。
这真的很烦人,因为据我所知,我正在正确地尝试访问商店,但它不起作用。
如有解释,将不胜感激。谢谢。
你的两种不同的方法有两个不同的错误。让我们先看看你的第一种方法:
---
<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']
}