Vue.js 在每个this.$router.push()调用上重新加载导航栏组件

Vue.js 在每个this.$router.push()调用上重新加载导航栏组件,vue.js,vuejs2,vue-component,vue-router,Vue.js,Vuejs2,Vue Component,Vue Router,我正在Vue.js应用程序中开发登录/注册系统。我希望在调用此时更新导航栏中的项目。$router.push“/” App.vue: <template> <div id="app"> <Navbar></Navbar> <router-view></router-view> <Footer></Footer> </div> </template>

我正在Vue.js应用程序中开发登录/注册系统。我希望在调用此时更新导航栏中的项目。$router.push“/”

App.vue:

<template>
  <div id="app">
    <Navbar></Navbar>
    <router-view></router-view>
    <Footer></Footer>
  </div>
</template>
以下是我如何重定向到另一个页面:

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!';
    });
小结:问题是当我调用self.$router.push“/”;时,Navbar中的isLoggedIn和currentUser没有得到更新;。这意味着装载和更新的函数不会被调用。它们只有在我手动刷新页面后才会更新。

请查看以下内容:


我希望您的导航栏组件可以跨路由重用,这样就不会调用其已装载和更新的组件。如果要对路由更改进行一些处理,请尝试使用beforeRouteUpdate。

我通过向导航栏组件添加:key=$route.fullPath解决了问题:

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();
    }
}
<template>
  <div id="app">
    <Navbar :key="$route.fullPath"></Navbar>
    <router-view></router-view>
    <Footer></Footer>
  </div>
</template>

我也面临同样的问题,无法找到任何解决办法。使用此选项。$router.go可刷新组件,因此无需手动重新加载。如果您解决了此问题,请让我知道。如果我在Navbar组件中放置beforeRouteUpdate,则使用self时不会调用它。$router.push“/”;。
<template>
  <div id="app">
    <Navbar :key="$route.fullPath"></Navbar>
    <router-view></router-view>
    <Footer></Footer>
  </div>
</template>