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
方法中可以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() }