【6月日新计划更文活动】第6天
嵌套 (多级) 路由
1、配置路由规则,使用 children 配置型:
// 创建一个路由器
const router = new VueRouter({
routes: [{
path: '/about', // 一级路由
component: About
},
{
path: '/home',
component: Home, // 一级路由
// 重定向配置,设置默认地址
redirect: "/about/info",
children: [ // 子路由
{
// 二级路由的path不要带斜杠:/
path: 'news',
component: News
},
{
path: 'message',
component: Message
}
]
}
]
})
2、跳转 (写完整路径)
<router-link to="/home/News" class="list-group" active-class="active"> News </router-link>
<router-link to="/home/Message" class="list-group" active-class="active"> Message </router-link>
路由目录下不区分大小写,统一转换成小写处理
路由传参
1、传递参数
<!-- 跳转路由并携带 query 参数,to的字符串写法 -->
<!-- <router-link :to="/home/Message/Detail?id=666$title= 你好"> 跳转 </router-link> -->
<!-- 跳转路由并携带 query 参数,to的对象写法 -->
<router-link
:to="{
path: '/home/message/detail',
query: {
id: 666,
title: 你好,
},
}"
>{{ n.title }}</router-link>
2、接收参数
$route.query.id
$route.query.title
携带参数和配置参数,不影响路由器配置
命名路由
1、作用:可以简化路由的跳转
2、使用: 1)、给路由命名:
{
path: '/home',
component: Home, // 一级路由
children: [ // 子路由
{
path: 'news',
component: News
// 路由异步加载方式
// component: () => impont('../views/content/xxx')
},
{
name: 'xinxi', //给路由命名
path: 'message',
component: Message,
children: [{
name: 'xiangqing', //给路由命名
path: 'detail',
component: Detail
}]
}
]
}
2)、简化跳转:
<!-- 简化前,需要配置完整的路径 -->
<router-link to="/home/message/detail“>跳转</router-link>
<!-- 路径用命名路由简写,直接通过名字跳转 -->
<router-link :to="{name: 'xiangqing'}">跳转</router-link>
<!-- 简化写法配合传递参数 -->
<router-link
:to="{
name: 'xiangqing',
query: {
id: 666
title: '你好',
},
}"
>跳转</router-link>
路由的 params 参数
1、配置路由,声明接收 params 参数
{
path: '/home',
component: Home,
children: [
{
path: 'news',
component: News
},
{
name: 'xinxi',
path: 'message',
component: Message,
children: [{
name: 'xiangqing',
path: 'detail/:id/:title', // 使用占位符声明接收 params参数
component: Detail
}]
}
2、传递参数
// 跳转并携带 params 参数,to的字符串写法
<router-link :to="`/home/Message/Detail/666/你好啊`">跳转</router-link>
// 跳转并携带 params 参数,to的对象写法
<router-link
:to="{
// path: '/home/message/detail', // 不允许写 path,只能使用name
name: 'xiangqing',
params: {
id: n.id,
title: n.title,
},
}"
>{{ n.title }}</router-link>
3、接收参数
<!-- params 传参 -->
<li>消息编号: {{ this.$route.params.id }}</li>
<li>消息编号: {{ this.$route.params.title }}</li>