配置路由器.之前每个



当用户单击箭头返回浏览器的上一页时,我尝试在主页上取回用户。

当我在页面上登录时,我无法使用浏览器的箭头返回。

我们建议我使用" 路由之前每个 "我不明白它是如何工作的。

主.js:

Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/login',
name: 'Login',
component: Login,
meta: { requiresAuth: true }
},
{
path: '/register',
name: 'Register',
component: Register,
},
{
path: '/complete_registration',
name: 'Complete Registration',
component: CompleteRegistration,
},
{
path: '/profile',
name: 'Profile',
component: Profile,
meta: { requiresAuth: true }
}
]
const router = new VueRouter({routes, mode: 'history'})
router.beforeEach((to, from, next) => {
if ( from.matched.some(record => record.meta.requiresAuth) ) {
alert('enter')
next('/');
} else {
next();
}
});

通过连接我,它会在警报的循环弹出窗口中显示我

Thomas Kleßen在他的评论中完全正确:

  1. 应仅将meta: { requiresAuth: true }添加到需要对用户进行身份验证的路由。登录页面不是这种情况(我猜也不是注册页面和主页页面(。
  2. router.beforeEach()您应该检查"目标"是否需要对用户进行身份验证,即to(而不是对应于您来自的页面的from(。

但是,您需要添加额外的检查:如果用户未通过身份验证,则需要将她/他重定向到登录页面。为此,您可以使用firebase.auth().currentUser,如下所示。在此处查看相应的 Firebase 文档。

const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/register',
name: 'Register',
component: Register
},
{
path: '/complete_registration',
name: 'Complete Registration',
component: CompleteRegistration
},
{
path: '/profile',
name: 'Profile',
component: Profile,
meta: { requiresAuth: true }
},
{
path: '/otherProtectedPage',
name: 'OtherProtectedPage',
component: OtherProtectedPage,
meta: { requiresAuth: true }
}
]
const router = new VueRouter({routes, mode: 'history'})
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record  => record.meta.requiresAuth)
const currentUser = firebase.auth().currentUser
if (requiresAuth && !currentUser) {
next('/login')
} else if (requiresAuth && currentUser) {
next()
} else {
next()
}
})

最新更新