1.配置
routes: [
{
path: '/',
name: 'home',
component:Home
},
{
path: '/about',
name: 'about',
//路由层级代码分割,生成分片(about.[hash].js)
//当路由访问时会进行懒加载
component:() => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
指定路由器
new Vue({
router,
render: h => h(App)
}).$mount('#app')
路由视图
<router-view />
导航链接
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
路由嵌套
//router.js
{
path: "/",
component: Home,
children: [{
path: '/list',
name: 'list',
component:List
}]
}
//Home.vue
<template>
<div class="home">
<h1>首页</h1>
<router-view></router-view>
</div>
</template>
动态路由
<template>
<div>
<h2>商品详情</h2>
<p>{{$route.params.id}}</p>
</div>
</template>
路由守卫(全局)
router.beforeach((to,from,next) => {
if(to.meta.auth && !window.isLogin){
if(window.confirm('请登录')){
window.isLogin = true;
next();
}else {
next('/')
}
}else {
next()
}
})
路由独享守卫
beforeEnter(to,from,next){
if(!window.isLogin){
}else{
next()
}
}
组件内的守卫
export default{
beforeRouteEnter(to,from,next){
// this在这里不能进入,因为是初始化阶段
},
beforeRouteUpdate(to,from,next){},
beforeRouteLeave(to,from,next){}
}
动态路由
//异步获取路由
api.getRoutes().then(routes => {
const routeConfig = routes.map(route => mapComponent(route);
router.addRoutes(routeConfig)
})
//映射关系
const comMap = {
'Home': () =>import("./view/Home.vue")
}
//递归替换
function mapComponent(route){
route.component = compMap[route.component]
if(route.children){
route.children = route.children.map(child => mapComponent(child))
}
return route
}