这是我参与「第四届青训营 」笔记创作活动的第5天
一、Vue路由简单介绍
路由:即一组映射关系(key – value),key为路径,value可能是function或component。
路由器:包含多个映射关系的组合。
SPA: 即单页面的web应用 (single page web application,SPA),整个应用只有一个页面,点击页面的导航链接不会刷新页面 只会做页面的局部更新。
路由可分为前端路由和后端路由:
1、前端路由:
理解:value是component,用于展示页面的内容;
工作过程:服务器接收到了一个请求,根据请求路径找到匹配的函数来去处理数据,返回响应式数据;
2、后端路由:
理解:value是function 用于处理客户提交的请求;
工作工程:服务器接收到了一个请求,根据请求路径找到匹配的函数来去处理数据,返回响应式数据;
二、路由配置
1、属性配置
export default new Router({
mode: 'history', //路由模式,取值为history与hash
base: '/', //打包路径,默认为/,可以修改
routes: [
{
path: string, //路径
component: Component; //页面组件
name: string; // 命名路由-路由名称
components: ( ComponentName | ()=>import('页面地址') ); // 命名视图组件
redirect: string | Location | Function; // 重定向
props: boolean | string | Function; // 路由组件传递参数
alias: string | Array<string>; // 路由别名
children: Array<RouteConfig>; // 嵌套子路由
beforeEnter?: (to: Route, from: Route, next: Function) => void; // 路由单独钩子
meta: any; // 自定义标签属性,比如:是否需要登录
icon: any; // 图标
// 2.6.0+
caseSensitive: boolean; // 匹配规则是否大小写敏感?(默认值:false)
pathToRegexpOptions: Object; // 编译正则的选项
}
]
})
2、嵌套子路由配置
例:
{
path:'/home',
component:home,
children:[
{
path:'news',
component:News
},
{
path:'messge',
component:Messge,
children:[
{
name:'hello'
path:'detail/:id/:title',
component:Detail
}
]
}
]
}
三、路由跳转
路由的跳转方式有3种。
1、标签路由router-link,需要配合router-view使用
<router-link :to="{name:'home'}">
2、编程式路由this.router.push。
this.$router.push('/home')
this.router.replace与this.router.push的用法相同,不同的是前者不会留下历史记录,而后者会。
3、this.$router.go、this.$router.forward和this.$router.back。
这三个的用法非常相似,this.$router.forward说跳转到历史记录的下一个页面,this.$router.back是返回到历史记录的上一个页面,this.$router.go可接收参数n,若n为正数则向历史记录中的下n个页面跳转,若n为负数则返回至本页的上n个页面。
四、路由传参
params参数:路由需要占位,程序就崩了,属于URL当中一部分
query参数:路由不需要占位,写法类似于ajax当中query参数
1、push方法传递参数
- 字符串形式传参
this.$router.push("/search/"+this.id+"?k="+this.id);
- 传递query参数
this.$router.push({path:'/search',query:{keyword:this.keyword}});
- 传递params参数
this.$router.push({name:'search',params:{keyword:this.keyword}});
- 传递query+params参数
this.$router.push({
name: "search",
params: { keyword: this.keyword },
query: { keyword: "ABC" },
});
2、router-link方法传递参数
query参数传递
<router-link :to="{
path:"/home/message/detail",
query:{
id:m.id,
title:m.title
}
}"/>
params参数传递
<router-link :to="{
path:"`/home/message/detail/${m.id}/${m.title}`"
params:{
id:m.id,
title:m.title
}
}"/>
注意:当为params传参时,路由配置需要更改为path:"detail/:id/:title。同时有一点,子路由的path路径不需要携带'/'。
获取传递的参数需要通过this.$route.query.xxx或者this.$route.params.xxx来接收。
五、总结
路由组件通常存放在pages或者views文件夹,一般组件通常放在components文件夹,通过切换路由隐藏了的路由组件 默认是被销毁,需要的时候再去挂载,每个组件都有自己的route,且里面存放着自己的路由信息,路由器router只能有一个,用于配置整个项目的路由规则。