之前的路由都是一级路由,即localhost:8080/home指向Home组件,localhost:8080/about指向About组件。
下面希望再给About组件下面加上两个路由,localhost:8080/about/user让About组件中显示AboutUser组件,localhost:8080/about/role让About组件中显示AboutRole组件。
views文件夹下新建AboutUser.vue文件和AboutRole.vue组件:
AboutUser.vue:
<template>
<div >
这是AboutUser页面
</div>
</template>
<script>
export default {
components: {
}
}
</script>
AboutRole.vue:
<template>
<div >
这是AboutRole页面
</div>
</template>
<script>
export default {
components: {
}
}
</script>
index.js文件改为下面:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: ()=>import('../views/Home.vue')
},
{
path: '/about',
name: 'About',
component: ()=>import('../views/About.vue'),
children:[{//定义About路由下的子路由
path:'user',
component:()=>import('../views/AboutUser.vue'),
},{
path:'role',
component:()=>import('../views/AboutRole.vue'),
}]
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
About.vue文件:
<template>
<div >
这是About页面
<br>
<router-link to="/about/user">AboutUser</router-link>//跳向AboutUser组件的路由链接
<br>
<router-link to="/about/role">AboutRole</router-link>//跳向AboutRole组件的路由链接
<br>
<router-view></router-view>//路由组件的显示位置
</div>
</template>
<script>
export default {
components: {
}
}
</script>