对于没有匹配到的路由,咱们通常会匹配到某个固定的页面,如404页面,在vue3中,咱们通常通过pathMatch来设置。如下:
// 办法一:
{
path: '/:pathMatch(.*)',
component: () => import ('../views/notFound.vue')
},
// 办法二
{
path: '/:pathMatch(.*)*',
component: () => import ('../views/notFound.vue')
},
办法二比办法一前面多了个“*”,他们的区别在于是否解析“/”。
如:当我拜访一个不存在的路由 “http://127.0.0.1:5173/#/homef…”时,
办法一
<template>
<div class=''>404 页面找不到了</div>
<!-- path: '/:pathMatch(.*)' -->
<!-- 输入为: homefdfsd/fesdfsd -->
<h1>{{$route.params.pathMatch}}</h1>
</template>
办法二
<template>
<div class=''>404 页面找不到了</div>
<!-- path: '/:pathMatch(.*)*' -->
<!-- 输入为: [ "homefdfsd", "fesdfsd" ] -->
<h1>{{$route.params.pathMatch}}</h1>
</template>
残缺代码如下
import {
createRouter,
createWebHashHistory
} from 'vue-router'
const routes = [
{
path: "/",
redirect: '/home'
},{
path: '/home',
component: () => import('../views/home.vue')
},
{
path: '/about',
component: () => import ('../views/about.vue')
},
// 办法一:
{
path: '/:pathMatch(.*)',
component: () => import ('../views/notFound.vue')
},
// 办法二
{
path: '/:pathMatch(.*)*',
component: () => import ('../views/notFound.vue')
},
]
const router = createRouter({
routes,
history:createWebHashHistory()
})
export default router
发表回复