1. 动态路由定义:
在router文件夹里面的index.js里定义动态路由:
const router = createRouter({
routes: [
{
path: '/test/:id',
name: 'test',
component: () => import('../views/content/test.vue')
}
]
其中:id就是我们插入动态id的位置,页面使用:
router.push({
path: `/test/${id}`
})
这样写无论id填了什么,都会跳转到以test.vue为基底的页面
a. 如果我们想限制id为number类型,需要使用路由独享守卫:
// util.js定义:
// 验证是否是数字
export function isNumber(val) {
let pattern = /^\d+$/;
if (pattern.test(val)) {
return true;
}
return false;
}
// router/index.js定义:
import { isNumber } from '@/assets/util.js'
const router = createRouter({
routes: [
{
path: '/test/:id',
name: 'test',
component: () => import('../views/content/test.vue'),
beforeEnter: (to, from, next) => {
if( isNumber(to.params.id) ) {
next()
} else {
next('/404')
}
}
}
]
b. 注意:页面动态路由组件复用,不再重复走生命周期,需要通过onBeforeRouteUpdate获取更新的路由后缀
import { onBeforeRouteUpdate } from "vue-router"
onBeforeRouteUpdate(async (to, from) => {
if (to.params.id !== from.params.id) {
// 进来这里表示动态路由的路由切换了,页面更新操作这里处理
}
})
2. 404路由定义
// 当访问的路径不存在
{
path: '/404',
name: '404',
component: () => import('../views/ErrorView.vue'),
},
// 通配,访问没有定义的路由都会走这里
{
path: '/:pathMatch(.*)',
redirect: '/404',
}