# Vue-Router 3.x
前言
补充一些官方文档中没有的,但是实际开发中最好需要了解的内容
# 1.路由模式
hash 模式
打包后的文件可以直接点击打开
history 模式
打包后的文件不能直接打开,需要在 nginx 上配置
abstract 模式
内容节点为空,可以做为鉴权页面
# 2.导航解析流程
- 导航被触发
 - 在失活的组件(即将离开的页面组件)里调用离开守卫 beforeRouteLeave
 - 调用全局的 beforeEach 守卫
 - 在重用的组件里调用 beforeRouteUpdate 守卫
 - 在路由配置里调用 beforeEnter
 - 解析异步路由组件
 - 在被激活的组件里调用 beforeRouteEnter
 - 调用全局的 解析守卫 beforeResolve
 - 导航被确认
 - 调用全局的后置守卫 afterEach 钩子
 - 触发 DOM 更新
 - 用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数
 
# 3.过渡效果
- 给所有路由设置过渡效果
 
<template>
  <transition name="router">
    <router-view />
    <router-view name="a"></router-view>
    <router-view name="b"></router-view>
  </transition>
</template>
<style lang="less">
.router-enter {
  opacity: 0;
}
.router-enter-active {
  transition: opacity 0.5s linear;
}
.router-enter-to {
  opacity: 1;
}
.router-leave {
  opacity: 1;
}
.router-leave-active {
  transition: opacity 0.5s linear;
}
.router-leave-to {
  opacity: 0;
}
</style>
 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
27
28
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
27
28
- 路由设置过渡效果
 
<template>
  <transition-group name="router">
    <router-view />
  </transition-group>
</template>
<style lang="scss">
.router-enter {
  opacity: 0;
}
.router-enter-active {
  transition: opacity 0.5s linear;
}
.router-enter-to {
  opacity: 1;
}
.router-leave {
  opacity: 1;
}
.router-leave-active {
  transition: opacity 0.5s linear;
}
.router-leave-to {
  opacity: 0;
}
</style>
 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
# 4.路由传参
# 4.1 拼接字符串传参
// 路由定义
{
  path: '/describe/:id',
  name: 'Describe',
  component: Describe
}
// 页面传参
this.$router.push({
  path: `/describe/${id}`,
})
// 页面获取
this.$route.params.id
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 4.2 通过params传参
 // 路由定义
{
  path: '/describe',
  name: 'Describe',
  omponent: Describe
}
// 页面传参
this.$router.push({
  name: 'Describe',
  params: {
    id: id
  }
})
// 页面获取
this.$route.params.id
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 4.3 通过query传参
 // 路由定义
{
  path: '/describe',
  name: 'Describe',
  component: Describe
}
// 页面传参
this.$router.push({
  path: '/describe',
  query: {
      id: id
  }
)
// 页面获取
this.$route.query.id
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 三种方案对比
- 方案二参数不会拼接在路由后面,页面刷新参数会丢失
 - 方案一和三参数拼接在后面,丑,而且暴露了信息
 
 
# 5.router-link
# 6.router-view
# 7.其他
# 7.1 对象转url
- 方式一:$router
 
const { href } = this.$router.resolve({ name: 'UserProfile', params: { userId: 123 } });
 1
- 方式二:原生方法
 
const href = url + '?' + new URLSearchParams(params).toString()
 1
- 方式三:qs插件
 
import qs from 'qs'
qs.parse('a=b&c=d');  => 转化为{ a: 'b', c: 'd'  }
qs.stringify({a: 'b', c: 'd'}) => 转化为‘a=b&c=d’
 1
2
3
4
2
3
4
let params = { c: 'b', a: 'd' };
qs.stringify(params)
// 结果是
'c=b&a=d'
 1
2
3
4
5
2
3
4
5