嵌套路由
嵌套路由即二级路由,作用在本身就是路由组件的组件中,可以提供无需刷新的部分页面跳转
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/user',
name: 'Login',
component: () => import('../components/footer.vue'),
children: [
{
path: '',
name: 'Login',
component: () => import('../components/login.vue'),
},
{
// 注意:这里的路径不能带有/,带有/的路径会被默认解析成根路径
path: 'reg',
name: 'Reg',
component: import('../components/reg.vue'),
},
],
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
<template>
<div>
<router-view></router-view>
<hr />
<h1>我是父路由</h1>
<div>
<!-- 通过router-link跳转,如果有需要也可以使用编程式路由导航 -->
<router-link to="/user">login</router-link>
<br>
<router-link to="/user/reg">Reg</router-link>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
</script>
<style scoped></style>
命名视图
在router配置文件中可以利用components配置项定义一些视图,当URL处于对应页面并且组件中具有与之相对应的router-view name属性时将这些组件挂载到页面上
<template>
<div>
<hr />
<h1>我是父路由</h1>
<div>
<router-view></router-view>
<router-view name="user1"></router-view>
<router-view name="user2"></router-view>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
</script>
<style scoped></style>
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Login',
component: () => import('../components/footer.vue'),
children: [
{
path: '',
name: 'Login',
components: {
// 当url为/且footer.vue中有<router-view>时挂载(没有name属性,因为是default)
default: () => import('../components/B.vue'),
},
},
{
path: 'reg',
name: 'Reg',
components: {
// 当url为/reg且具备对应的<router-view name="组件名">时挂载
user1: () => import('../components/login.vue'),
user2: () => import('../components/reg.vue'),
},
},
],
},
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
export default router
效果图: