In my component I'm trying to access the getters from my auth module.
This is the getter function in store/auth.js
getters: {
isAuthenticated: (state) => !!state.token,
},
And here is how I trying to access and display this data
// 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',
]),
},
and in the devtools this is the error i am getting ' Property or method "isAuthenticated" is not defined on the instance but referenced during render.' I'm really not sure why and not sure how to access this data, in the Vue debugger i can see that the getter works and is returning true.
I have tried other ways to access the data such as
isAuthenticated: () => this.$store.getters.isAuthenticated // and this.$store.getters.auth.isAuthenticated
but this gives a different error saying typeError: Cannot read property '$store' of undefined
when i try to access the computed function in the template.
This is really annoying because to my knowledge i am correctly trying to access the store and its not working.
An explanation would be greatly appreciated. Thanks.
You have two different errors in your two different approaches. Let's see your first approach first:
---
<span
v-if='this.isAuthenticated'
---
computed: {
...mapGetters([
'auth/isAuthenticated',
]),
}
---
Here, your problem is that you're trying to map a namespaced getter, but trying to access the attribute without the namespace. You can work around this by using an object parameter for the mapGetters
function:
computed: {
...mapGetters({
isAuthenticated: 'auth/isAuthenticated',
}),
}
In your second approach, you almost get it right, but you run into a different set of issues:
isAuthenticated: () => this.$store.getters.isAuthenticated
First of all, if the module is namespaced, the correct way to access the getter would be this.$store.getters['auth/isAuthenticated']
.
Apart from that, you should not use arrow functions in Vue components, since the this
context is lost (it points to the function rather than the Vue instance). You need to use a regular function.
Combining both of these fixes, the result would be:
isAuthenticated(){
return this.$store.getters['auth/isAuthenticated']
}