配置参数
使用路由
1 |
|
路由配置
1 |
import VueRouter from 'vue-router' |
属性
- this.$route.name // 当前路由
- params.pid // 获取路由参数
- hash // 获取当前url
- query // 查询参数
1 |
// 监听路由变化 |
方法
this.$router.push()
- onComplete 导航成功完成后执行
- onAbort
- 路由相同,参数不同,使用beforeRouteUpdate响应变化
1
2
3
4
5
6
7
8// 字符串
router.push('home')
// 对象,path情况下忽略params
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
go(n)
- back()、go(-1)
- replace()
beforeEach((to, from, next) => {}) 监听路由更新,跳转路由前的入口控制,可用于权限判断
- to 下一个路由
- from 当前路由
- next
- next() 下一个钩子,直到next()都执行完,才确认跳转
- next(false) 中断跳转
- next(‘/‘) 跳转到指定路由
响应路由
导航完成后获取数据
created中获取,并展示loading状态
1 |
<template> |
导航完成前获取数据
beforeEach,获取后next()
路由懒加载
- 异步组件、
- webpack代码分割
1
2
3
4
5
6
7
8
9
10
11// Foo.vue
const Foo = () => Promise.resolve({
// ... 组件定义对象
})
// 引用组件,Babel需要添加 syntax-dynamic-import解析语法
const Foo = () => import('./Foo.vue')
const router = new VueRouter({
routes: [
{ path: '/foo', component: Foo }
]
})