vue Router
导航
组件
<router-link to="">
,相当于<a href="/#/class/123">go to class</a>
- 用法:
<router-link to="/classView/123">go to class</router-link>
<router-link :to="{ name: 'classView' }">go to class</router-link>
编程式导航
this.$router.go(n);
前进或后退n步,n为整数this.$router.repleace();
用法和this.$router.push相同,但是不会向history里面添加新的记录this.$router.push()
会向history栈添加记录- 方法一:刷新后会丢失携带的参数
this.$router.push({
name: 'classView',
params: {
id: id
}
})
router.js
{
path: '/classView',
name: 'classView',
component: classView
}
获取参数
this.$route.params.id
- 方法二:页面刷新数据不会丢失
this.$router.push({
path: `/classView/${id}`,
})
router.js
{
path: '/classView/:id',
name: 'classView',
component: classView
}
获取参数
this.$route.params.id
- 方法三:参数显示在url后面
this.$router.push({
path: '/classView',
query: {
id: id
}
})
router.js
{
path: '/classView',
name: 'classView',
component: classView
}
获取参数
this.$route.query.id
hook
- 全局前置守卫
router.beforeEach
- 全局后置钩子
router.afterEach
- 路由独享的守卫
beforeEnter
- 组件内的守卫
beforeRouteEnter
、beforeRouteUpdate
、beforeRouteLeave
- 引用知乎上的一篇文章,学习一下。vue-router导航守卫。
路由导航的整体流程
- 导航被触发。
- 在失活的组件里调用 beforeRouteLeave 守卫。
- 调用全局的 beforeEach 守卫。
- 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
- 在路由配置里调用 beforeEnter。
- 解析异步路由组件。
- 在被激活的组件里调用 beforeRouteEnter。
- 调用全局的 beforeResolve 守卫 (2.5+)。
- 导航被确认。
- 调用全局的 afterEach 钩子。
- 触发 DOM 更新。
- 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。