在vue-router中,多级路由有如下两种写法:
- 直接多级路由
{
path: '/home/comp',
name: 'comp',
component: () => import('../common/comp.vue'),
meta: {
name: 'comp'
}
}
- 以子路由的形式
{
path: '/home',
name: 'home',
component: home,
meta: {
name: 'napier'
},
children: [
{
path: 'comp',
name: 'comp',
component: () => import('../common/comp.vue'),
meta: {
name: 'comp'
}
}
]
}
两者有什么区别呢?我们以实例说明:
- 新建home.vue,代码如下:
<div class="home-content">
home 的内容区
<router-view></router-view>
</div>
- 新建comp.vue,代码如下:
<div class="comp-content">
comp的内容区
</div>
-
在router.js中创建路由, 代码如下
如果创建如下多级路由,则comp的内容会独立于home显示在新页面中:
{
path: '/home/comp',
name: 'comp',
component: () => import('../common/comp.vue'),
meta: {
name: 'comp'
}
}
运行页面显示结果:
而如果创建如下子路由,则comp的内容会显示在home组件的router-view的位置:
{
path: '/home',
name: 'home',
component: home,
meta: {
name: 'Mike'
},
children: [
{
path: 'comp',
name: 'comp',
component: () => import('../common/comp.vue'),
meta: {
name: 'comp'
}
}
]
}
运行页面显示结果:
那么,如果我们如果在router.js中同时定义路上两种形式的路由,然后在页面上访问 /home/comp 时,页面上会显示什么内容呢?两者优先级谁高?
答案是:谁先定义,就显示谁对应的内容。
不管什么形式的内容,匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高。