vue 进阶之路由
当我们想用vue来创建单页面应用的时候,我们就可以用vue-router来建立起路由来选择将哪个组件映射到当前页面。
其中路由用到的最多的就是<router-view></router-view>
设置路由渲染部分。
用<router-link to="/index">index</router-link>
来触发,这个类似于一个a标签。点击跳转
最基本的路由应用就是:
- 定义路由
var router = new VueRouter({
routes: [
{
path: '/index',
component: index //'index'为引入的组件
},
]
})
- 挂载路由到实例上
new Vue({
router,
el: '#app',
render: h => h(App)
})
路由如何放参数
例如:
var router = new VueRouter({
routes: [
{
path: '/index:id',//冒号来设置参数
component: index //'index'为引入的组件
},
]
})
路径'/index/110'和'index/120'访问的都是相同的路由,映射一样的组件。
同时参数是在this.$route.params 里面。如果是'/index/110' ---->this.$route.params.id = 110
嵌套路由
在网页中经常会用到子目录,在路由中可以用嵌套路由,在VueRouter 的参数中使用 children。
例如:
var router = new VueRouter({
routes: [
{
path: '/index',
component: index,
children: [
{path: '/index/home',component: home},
{path: '/index/blog',component: blog}
]
},
]
})
这就是一个嵌套组件。通过访问'index/home'来触发映射home组件'index/blog'来映射blog组件
重定向
在网页开发中,我们经常会用重定向来防止链接错误。路由中也有重定向功能
var router = new VueRouter({
routes: [
{
path: '/', redirect: '/index'
},
]
})
别名
在开发中,会用到两个不一样的地址,指向同一个页面。
var router = new VueRouter({
routes: [
{
path: '/index',
component: index,
alias: '/home'
},
]
})
访问/index和/home都会映射index组件
过渡
我们可以设置路由跳转的时候动画效果。
<transition :name='slide-right'>
<router-view></router-view>
</transition>
滚动
我们可以设置跳转完成后,页面滚到哪个位置;
router 对象中有:
scrollBehavior (to, from, savedPosition) { //to,from 路由对象,第三个参数 savedPosition 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时用。
return { x: 0, y: 0 }//滚动的位置
}
路由懒加载
结合 Vue 的 异步组件 和 Webpack 的 code splitting feature, 轻松实现路由组件的懒加载。
把路由对应的组件变成异步组件
const Foo = resolve => {
// require.ensure 是 Webpack 的特殊语法,用来设置 code-split point
// (代码分块)
require.ensure(['./Foo.vue'], () => {
resolve(require('./Foo.vue'))
})
}
或者
const Foo = resolve => require(['./Foo.vue'], resolve)
//然后直接定义路由,什么都不用改