获取 routeView 的默认路由路径
解读如下代码:
const pageRecord = route.matched.find((record) => record.path !== "/" && record.components?.default);
return pageRecord ? pageRecord.path : route.path;
route.matched:获取当前 URL 匹配到的所有路由记录的数组,按照从父路由到子路由的顺序排列;
例如路由定义如下:
const routes = [
{
path: '/',
component: Layout,
children: [
{
path: 'system',
component: SystemLayout,
children: [
{
path: 'user',
component: UserPage
}
]
}
]
}
]
则 route.matched 获取到的数组如下:
[
{
path: '/',
component: Layout
},
{
path: '/system',
component: SystemLayout
},
{
path: '/system/user',
component: UserPage
}
]
record.path !== "/": 表示排除根布局;
record.components?.default:从路由记录中获取默认的页面组件,此处的组件就是 vue 页面;
例如下:一个路由有多个 .vue 页面组件,则 default 获取默认的那个:
{
path: "/layout",
components: {
default: MainContent, // 对应渲染到 <router-view />(无 name)
header: Header, // 对应渲染到 <router-view name="header" />
sidebar: Sidebar, // 对应渲染到 <router-view name="sidebar" />
}
}
例如下:一个路由只有一个 .vue 页面组件,则 default 获取的就是这唯一的 .vue 页面组件:
{
path: "exam-score",
name: "ExamScore",
component: () => import("@/views/exam-score/ExamScore.vue")
}
例如下:路由没有对应的 .vue 页面组件时,则 record.components?.default 返回 undefined
{
path: "exam-score",
name: "ExamScore",
redirect:[
// .....
]
}