# vue-router的api
# 路由对象
# 什么是路由对象
- 一个路由对象 (route object) 表示当前激活的路由的状态信息。
- 表示:
$route
- 包含:
- 当前URL解析得到的信息。
- URL匹配到的路由纪录。
- 路由对象是不可变的,每次成功导航后,都会产生一个新的对象。
# 路由对象的属性
应用见vue-router文档 声明式导航
$route.path
- 类型:
String
- 对应当前路由的绝对路径。例如:
/user/user1
- 类型:
$route.params
- 类型:
Object
- 包含了动态片段和全匹配片段,如果没有路由参数,就是一个空对象。
- 类型:
$route.query
- 类型:
Object
- 表示 URL 查询参数。例如,对于路径
/user?id=1
,则有$route.query.id == 1
,如果没有查询参数,则是个空对象。
- 类型:
$route.hash
- 类型:
String
- 当前路由的 hash 值 (带 #) ,如果没有 hash 值,则为空字符串。
- 类型:
$route.matched
- 类型:数组
- 包含当前路由的所有嵌套路径片段的路由记录,即配置路由实例时routes 选项中数组中的对象副本 (还有在 children 数组)。
$route.name
- 类型:
String
- 当前路由的名称,如果没有为空字符串。
- 类型:
$route.redirectedFrom
- 如果存在重定向,即为重定向来源的路由的名字
示例:
//使用声明式导航<router-link></router-link>来跳转路由
//不传参
<router-link to="/home">home</router-link>
//1. 使用动态路由参数传值到路由
// 参数存在$route.params中
<router-link to="/user/1">user1</router-link>
//2. 使用查询参数传值到路由
// 查询参数存在$route.query中
<router-link to="/cars?name=BMW&price=800000">BMW</router-link>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
const router = new VueRouter({
routes: [
{ path: '/home', component: Home },
{ path: '/user/:id', component: User },
{ path: '/cars', component: Cars }
]
});
//下面为三个不同的组件
const Home = {
template: `<h2>This is the page of home</h2>`,
created() {
console.log(this.$route);
}
};
const User = {
template: `<h2>This is the page of user {{$route.params.id}}</h2>`,
created() {
console.log(this.$route);
}
};
const Cars = {
template: `<h2>This is the page of Car {{$route.query.name}}</h2>`,
created() {
console.log(this.$route);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
结果分析 console.log(this.$route)
首先理解一句话:
每次成功导航后,都会产生一个新的路由对象$route
,也就是上例中,每跳转到一个路由,就基于本次的路由跳转创建一个新的$route。
不传参:

使用动态路由参数传参:
- 动态路由参数的值由
$route.params
接收。 - 属性id为上面设置的动态路由参数(配置routes选项中path值加冒号那个)。
- 如果有多个路由与该路由一样映射User组件,就是根据该属性id值的不同来区分的。
使用查询参数:
- 查询参数的值由
$route.query
接收。