Reputation: 59
I have a store.js
file that have the following state and getter:
state: {
isLoggedIn: false,
user: {}
},
getters: {
getUserId: state => state.user.id
},
After a user is logged in, the isLoggedIn
becomes true and user
is populated with the user's info as seen in image below:
As you can see I have a getter, in the store.js
that retrieves the correct ID but when I go to use this in my component, it comes up as undefined
.
My component looks like this:
const id = this.$store.getters.getUserId;
console.log(id);
How can I use the value of getUserId
in my component?
Upvotes: 0
Views: 641
Reputation: 198
I limit myself only to solving the problem based on the interpretation of the code provided
Solution 1:
const id = this.$store.getters.getUserId; I agree with the comment (kissu), but well regardless of where: in a hook, a method... You can use mapGetters in a computed property. Import:
import {mapGetters} from 'vuex // add this line in your component
<template>
...
UserId: {{ getUserId }}
...
</template>
<script>
import {mapGetters} from 'vuex
.
.
computed: {
...mapGetters(['getUserId']) // Also can use namespaces if preferred
}
...
</script>
Solution 2
You can used directly in DOM
<template>
...
UserId: {{ $store.getters.getUserId }}
...
</template>
I hope it will be useful
Upvotes: 1