Michael Harper
Michael Harper

Reputation: 65

Reload navbar component on every this.$router.push() call

I developing a login/registration system in my Vue.js app. I want the items in navbar to be updated when I call this.$router.push('/').

App.vue:

<template>
  <div id="app">
    <Navbar></Navbar>
    <router-view></router-view>
    <Footer></Footer>
  </div>
</template>

Navbar component:

export default {
    name: "Navbar",
    data: function() {
        return {
            isLoggedIn: false,
            currentUser: null
        }
    },
    methods: {
        getAuthInfo: function() {
            this.isLoggedIn = this.auth.isLoggedIn();
            if (this.isLoggedIn) {
                this.currentUser = this.auth.currentUser();
            }
        }
    },
    mounted: function() {
        this.getAuthInfo();
    },
    updated: function() {
        this.getAuthInfo();
    }
}

Here is how I redirect to another page:

const self = this;
this.axios
    .post('/login', formData)
    .then(function(data) {
        self.auth.saveToken(data.data.token);
        self.$router.push('/');
    })
    .catch(function(error) {
        console.log(error);
        self.errorMessage = 'Error!';
    });

SUMMARY: The problem is that isLoggedIn and currentUser in Navbar don't get updated when I call self.$router.push('/');. This means that functions mounted and updated don't get called. They are updated only after I manually refresh the page.

Upvotes: 1

Views: 2540

Answers (2)

Michael Harper
Michael Harper

Reputation: 65

I solved the problem with adding :key="$route.fullPath" to Navbar component:

<template>
  <div id="app">
    <Navbar :key="$route.fullPath"></Navbar>
    <router-view></router-view>
    <Footer></Footer>
  </div>
</template>

Upvotes: 5

bernie
bernie

Reputation: 10390

Check this out from the docs:

beforeRouteUpdate (to, from, next) {
  // called when the route that renders this component has changed,
  // but this component is reused in the new route.
  // For example, for a route with dynamic params `/foo/:id`, when we
  // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
  // will be reused, and this hook will be called when that happens.
  // has access to `this` component instance.
},

I expect your Navbar component is reused across routes so its mounted and updated are not called. Try using beforeRouteUpdate if you want to do some processing on route change.

Upvotes: 1

Related Questions