我在Vue.js应用程序中开发了一个登录/注册系统。我希望在致电this.$router.push('/')
时更新导航栏中的项目。
App.vue:
<template>
<div id="app">
<Navbar></Navbar>
<router-view></router-view>
<Footer></Footer>
</div>
</template>
导航栏组件:
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();
}
}
这是我重定向到另一页的方法:
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!';
});
摘要::问题是,当我调用isLoggedIn
时,Navbar中的currentUser
和self.$router.push('/');
没有得到更新。这意味着不会调用函数mounted
和updated
。只有在我手动刷新页面后,它们才会更新。
答案 0 :(得分:1)
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.
},
我希望您的Navbar组件可在路线之间重用,因此不会调用其mounted
和updated
。如果要对路由更改进行一些处理,请尝试使用beforeRouteUpdate
。
答案 1 :(得分:0)
我通过向Navbar组件添加:key="$route.fullPath"
解决了这个问题:
<template>
<div id="app">
<Navbar :key="$route.fullPath"></Navbar>
<router-view></router-view>
<Footer></Footer>
</div>
</template>