1

我一直在尝试修复这个 vue-router 警告,但没有成功:

从“/”到“/”时,在一个导航守卫中多次调用“下一个”回调。它应该在每个导航守卫中准确调用一次。这将在生产中失败。

我已经阅读了官方文档(https://next.router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards),但是在进行建议的更改时,我不断获得无限的下一个循环,所以我我显然做错了什么。

我想做的是:让未经身份验证的用户只能导航到“/”路线。如果他们尝试进入受保护的路线,则会被重定向到“/”。让经过身份验证的用户直接登陆“/mapping”并跳过“/”路线。然后他们可以导航到任何受保护的路线。

我用“let user = projectAuth.currentUser”验证身份验证。

提前感谢您的提示

import { createRouter, createWebHistory } from 'vue-router'
import Mapping from '../views/Mapping.vue'
import Home from '../views/Home.vue'
import TestDthree from '../views/TestDthree.vue'
import Testpage1 from '../views/Testpage1.vue'
import { projectAuth } from '../firebase/config'



// auth guard or route guard
// requires to be authenticated
const requireAuth = (to, from, next) => {
  let user = projectAuth.currentUser
  if(!user){
    next({name:'Home'})
  }
  next()
}


// no auth needed
// bypassed Home for any logged in user
const requireNoAuth = (to, from, next) => {
  let user = projectAuth.currentUser
  if(user){
    next({name:'Mapping'})
  }
  next()
}







const routes = [ 
  {
    path: '/',
    name: 'Home',
    component: Home,
    beforeEnter: requireNoAuth
  },
  {
    path: '/mapping',
    name: 'Mapping',
    component: Mapping,
    beforeEnter: requireAuth
  },
  {
    path: '/testpage1',
    name: 'Testpage1',
    component: Testpage1,
    beforeEnter: requireAuth
  },
  {
    path: '/loadLegacyData2',
    name: 'LoadLegacyData2',
    component: () => import( '../views/LoadLegacyData2.vue'),
    beforeEnter: requireAuth
  },
  {
    path: '/testmap',
    name: 'TestDthree',
    component: TestDthree,
    beforeEnter: requireAuth
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


export default router

4

2 回答 2

2

只需在中添加回报requireAuth

  const requireAuth = (to, from, next) => {
    let user = projectAuth.currentUser
    if(!user){
      next({name:'Home'})
      return
    }
    next()
    return
  }
于 2022-01-11T13:58:59.790 回答
0

你必须检查你是否已经在页面上,否则它将无限循环。像这样的东西

const requireAuth = (to, from, next) => {
    let user = projectAuth.currentUser
    if(!user && from.name !== 'Home'){
       next({name:'Home'})
    }
    next()
}
于 2022-01-11T12:25:47.487 回答