[Vuejs]-Reactivity issue in vue component

1👍

I think in general the structure isn’t working out here. It’s true like some others said that it’s better to use a computed property but this is not the issue right here.

Basically, as soon as the app loads you should call auth.getUser(), for example inside your mounted() or created() handler;

// Sidebar.vue or your Root new Vue()
{
    data() {
        return {
            user: null,
        };
    },
    created() {
        this.user = auth.getUser();
    },
}
<button
 type="button"
 v-if="user"
 @click="logout"
 class="btn btn-outline-light">

You can add this to your sidebar component, but it’s usually better to handle authentication on the application root component or use Vuex because you often need to know whether or not you’re logged in on multiple parts of the app.

If you want to add the created() handler and user variable to your root component you can access it like so;

<button
 type="button"
 v-if="$root.user"
 @click="logout"
 class="btn btn-outline-light">
👤Thieu

0👍

Use computed property to bind with v-if like this:

computed: {
  loggedIn () {
    return !(auth.getUser() === null)
  }
}

More here: https://v2.vuejs.org/v2/guide/computed.html

👤MiKr13

0👍

Computed cannot be used here, a computed property will never update, because return !(auth.getUser() === null)is not a reactive dependency.

In comparison, a method invocation will always run the function whenever a re-render happens. The solution then, is to re-render the side bar as documented by Michael Thiessen:

<side-bar :key="loggedIn()"/>

Leave a comment