配置父子路由關系,A.vue和B.vue是Main.vue的子組件:
{
path: '/main/',
name: 'main',
component: () => import('components/Main.vue'),
children: [
{
path: 'a',
name: 'a',
component: () => import('components/A.vue')
},
{
path: 'b',
name: 'b',
component: () => import('components/B.vue')
}
]
}
編寫兩個簡單的子組件:
- 一個是A.vue
<template>
<h1>This is A</h1>
</template>
<script>
export default {
name: "A"
}
</script>
<style>
</style>
- 一個是B.vue
<template>
<h1>This is B</h1>
</template>
<script>
export default {
name: "B"
}
</script>
<style>
</style>
- 然后編寫父組件Main.vue
<template>
<div style="margin-left: 300px;">
<router-link :to="{name:'a'}"><span style="font-size: 50px;">A</span></router-link>
<router-link :to="{name:'b'}"><span style="font-size: 50px;">B</span></router-link>
<router-view></router-view>
</div>
</template>
<script>
</script>
<style>
</style>
路由導航<router-link :to="{name:'a'}">
和<router-link :to="{name:'b'}">
導向到子路由。
<router-view></router-view>
用來顯示子路由對應的內容,即子路由對應頁面的顯示區域。
修改路由配置,添加redirect: {name: "a"}
,使輸入/main/時自動重定向到/main/a
{
path: '/main/',
name: 'main',
component: () => import('components/Main.vue'),
redirect: {name: "a"},
children: [
{
path: 'a',
name: 'a',
component: () => import('components/A.vue')
},
{
path: 'b',
name: 'b',
component: () => import('components/B.vue')
}
]
}