首页 > 解决方案 > 配置 router.beforeEach

问题描述

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

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

我们建议我使用“路由 BeforeEach”我不明白它是如何工作的。

主.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();
  }
});

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

标签: javascriptfirebasevue.jsfirebase-authenticationvuex

解决方案


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()
    }
})

推荐阅读