前言
vue-router 控制页面跳转, 重点在于 "更新视图但不重新请求页面", 并且拥有懒加载功能.
推荐配置写法 (开启页面跳转至组件, 懒加载)
- export default new Router({
- routes: [{
- path: '/home',
- name: 'home',
- component: () => import('home.vue') // 懒加载
- }]
- })
之后在 App.vue 中插入 < router-view></router-view > 既可.
事件跳转
在点击等事件触发时执行方法, 另外如果需要传递参数, 则可以在 push 方法中以 query: { a: '111'}
this.$router.push( { path: '/home' } ) // 该处 path 对应在配置中的路径
当然也可以用 链接 的方式进行跳转
<router-link to="/home"></router-link>
动态路由
- export default new Router({
- routes: [{
- path: '/home/:id',// 传参, 当 / 后面接任何字符串均可
- name: 'home',
- component: () => import('home.vue')
- }]
- })
另组件内获取参数的方法
<h1>{{ $route.params.id }}</h1>
嵌套路由
当你需要只改变布局中的一部分页面时
- routes: [{
- path: '/home',
- name: 'home',
- component: () => import('home.vue')
- children: [{
- path: '/child',
- component: () => import('child.vue')
- }]
- }]
之后在 home.vue 中插入 < router-view></router-view > 既可
push() 传递参数
在事件跳转中我们说到 push 方法中可以 query: { a: '111'} 进行参数传递
this.$router.push( { path: '/home' , query: { a: '111'}} )
此外我们还能用 params : { a: '111'} 进行传参, 但是注意此时 push 方法不再用 path, 而用 name, 否则会有错误!
this.$router.push( { name: 'home' , params: { a: '111'}} )
事实上, vue-router 的用法并不仅仅只有这些, 并且他有自己的钩子函数, 例如可以利用 beforeEach 记录跳转的路径, 同时如果不加入 next() 方法则路由无法跳转, 类似于 Generator 函数的驻点
- router.beforeEach(to, from, next) => {
- console.log(to.path)
- next()
- }
来源: http://www.jianshu.com/p/79fda8691f78