路由配置
router-index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
const routes: Array<RouteRecordRaw> =
//可以把静态固定路由放在一个单独文件引入
[
{
path: '/login',
name: 'Login',
meta: {
title: '登录',
keepAlive: true,
requireAuth: false//表明该路由是否需要登录验证
},
component: () => import('../view/login/login.vue')
},
{
path: '/:pathMatch(.*)*',
name: '404',
component: () => import('../view/404/index.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes,
//路由切换滚动行为
scrollBehavior() {
return {
top: 0,
left:0
}
}
});
export default router;
对于没有匹配到的路由,我们通常会匹配到某个固定的页面,
如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>