常规参数只匹配url片段时间的字符,用/分割。如果我们想匹配任意路径,我们可以使用自定义的路径参数正则表达式,在路径参数后面的括号中加入正则表达式。
如果输入的路径错误则跳转到404页面
首先,在src文件夹下的components文件夹中创建NotFound.vue文件,如图是目录列表:

在NotFound.vue文件中代码如下:
<template>
<h2>
找不到页面
</h2>
</template>
在router文件下的index.js文件中代码如下:
import { createRouter,createWebHashHistory } from "vue-router";
const routes=[{
path:"/home",component:()=>import("../components/Home.vue")
},{
path:"/about",component:()=>import("../components/About.vue")
},{
path:"/user/:id",component:()=>import("../components/User.vue")
},{
//使用正则的方式,匹配任意的
path:"/:path(.*)",component:()=>import("../components/NotFound.vue")
}
]
const router =createRouter({
history:createWebHashHistory(),
routes,
})
export default router
结果如下:

解决了如果因路径输入错误,从而都跳转到404页面。
8181

被折叠的 条评论
为什么被折叠?



