Reputation: 1263
I understand how to use a Vue plugin like vue-session for creating and holding a session. But I am not sure how to deal with user data from a session, especially when it comes to reactivity. E.g.: I have a User component in the navigation header which displays the currently logged in user. How do I ensure that the username shown via this User component is reactive? In other words: if somewhen while using the application a login happens (to enable restricted functions), then how can the User component know?
Is $watch
the right way to go? But this means polling, doesn't it?
How can I ensure that the user data stored in the session plugin is reactive?
Imagine such a component which visualises the logged in user:
<template>
<div>
<div v-if="user.username">
Logged in as {{user.username}}
</div>
<div v-else>
Not logged in.
</div>
</div>
</template>
<script>
export default {
name: "LoggedInUser",
data() {
return {
user: {
username: null,
email: null
}
};
},
computed: {
user() {
return { this.$session.user };
}
}
};
</script>
I do not want to determine the session user in the create
method because it should be reactive (reactive to logout/login).
What's the best option for that?
Upvotes: 1
Views: 1823
Reputation: 10390
The best way is to use a computed property (like you did) that uses a getter from a Vuex store (or a mapped getter in Vuex speak). All the state stored in a Vuex store is reactive so you'll get what you're looking for.
Instead of storing the current user in the $session
from vue-session, it would be stored in the Vuex store.
Vuex: https://vuex.vuejs.org/
I had a quick look at that plugin and its source (only ~100 lines) and there is definitely no reactivity option in there. It's essentially a convenience interface over window.localStorage
. $watch
only works on reactive data (e.g. a component's data
object) which is not provided by this plugin.
Reactivity could be retrofitted in there with Vue.observable(object) I guess though.
A nice read on reactivity: https://stackoverflow.com/a/54492326/1030527
Upvotes: 2