闽公网安备 35020302035485号
router.beforeEach((to, from, next) => {
if (isLogin() && to.name === 'Login') {
next('/')
} else if (!isLogin() && to.name !== 'Login') {
next({ name: 'Login' })
} else {
next()
}
})
新版全局路由钩子的使用方法router.beforeEach((to, from) => {
if (isLogin() && to.name === 'Login') {
return '/'
}
if (!isLogin() && to.name !== 'Login') {
return {
name: 'Login',
}
}
return true
})
可见新版全局路由钩子并不需要next方法来进行重定向,即使next方法仍可使用,可能在未来会被废弃,使用return 会更加适应新版本的变化,而且可以让代码更加清晰。
import { createRouter, createWebHistory } from 'vue-router'
import constantRoutes from './constant-routes';
import { getDynamicRoutes } from '@/api/index';
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
redirect: '/home'
},
...constantRoutes // 静态路由包含了404页面,当所有页面都匹配不上时,会重定向到404
]
})
// 堆代码 duidaima.com
// 是否已经添加动态路由
let isAddRoutes = false
router.beforeEach(async (to, from, next) => {
if (!isAddRoutes) {
isAddRoutes = true
const dynamicRoutes = await getDynamicRoutes()
dynamicRoutes.forEach(route => {
router.addRoute({
path: route.path,
name: route.name,
component: route.component
})
})
next({ ...to, replace: true })
} else {
next()
}
})
export default router
解决第一次进入动态路由页面会渲染404页面的问题// 是否已经添加动态路由
let isAddRoutes = false
router.beforeEach(async (to, from, next) => {
if (!isAddRoutes) {
isAddRoutes = true
const dynamicRoutes = await getDynamicRoutes()
dynamicRoutes.forEach(route => {
router.addRoute({
path: route.path,
name: route.name,
component: route.component
})
})
// 手动添加404页面
router.addRoute({
path: '/:pathMatch(.*)*',
name: 'not-found',
component: () => import('../views/NotFoundView.vue')
})
next({ ...to, replace: true })
} else {
next()
}
})
这样,貌似就没有问题了,页面能够正常渲染,但是控制台会出现警告这是因为,在等待路由加载的过程中,当前进入的路由是动态的,而我们的动态路由配置尚未加载完毕,未匹配中任何的路由,to.matched为空,所以vue-router就抛出了这个警告。
export default [
{
path: '/home',
name: 'home',
component: () => import('../views/HomeView.vue')
},
// 可以在静态路由中写死该配置
{
path: '/:pathMatch(.*)*',
name: 'not-found',
component: () => import('../views/NotFoundView.vue')
}
]
// 是否已经添加动态路由
let isAddRoutes = false
router.beforeEach(async (to, from, next) => {
if (!isAddRoutes) {
isAddRoutes = true
const dynamicRoutes = await getDynamicRoutes()
dynamicRoutes.forEach(route => {
router.addRoute({
path: route.path,
name: route.name,
component: route.component
})
})
// 返回to.fullPath,当添加完所有的动态路由后,触发重定向
next(to.fullPath)
} else {
next()
}
})
使用V4新版的写法,我们可以将next函数,换成return,代码会更加清晰/ 判断否已经添加动态路由,避免重复添加
let isAddRoutes = false
router.beforeEach(async (to, from) => {
if (!isAddRoutes) {
isAddRoutes = true
const dynamicRoutes = await getDynamicRoutes()
dynamicRoutes.forEach(route => {
router.addRoute({
path: route.path,
name: route.name,
component: route.component
})
})
// 堆代码 duidaima.com
// 返回to.fullPath,当添加完所有的动态路由后,触发重定向
return to.fullPath
}
return true
})
总结