使用
// router.js
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
mode: 'hash', // 模式:hash | history | abstract
base: process.env.BASE_URL, // http://localhost:8080
routes: [
{
path: '/',
name: 'home',
component: Home,
children: [
{ path: "/list", name: "list", component: List },
{ path: "detail/:id", component: Detail, props: true },
]
},
{
path: '/about',
name: 'about',
meta: { auth: true },
// 路由层级代码分割
// 生成分片(about.[hash].js)
// 当路由房问时会懒加载.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
})
配置
import Home from './views/Home.vue'
const routes = [
{
path: '/',
name: 'home',
component: Home,
children: [
{ path: "/list", name: "list", component: List },
{ path: "detail/:id", component: Detail, props: true },
]
},
{
path: '/about',
name: 'about',
meta: { auth: true },
// 路由层级代码分割
// 生成分片(about.[hash].js)
// 当路由房问时会懒加载.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
指定路由器
// main.js
new Vue({
router,
render: h => h(App)
}).$mount("#app");
路由视图
导航链接
Home
About
路由嵌套
应用界面通常由多层嵌套的组件组合而成。同样的,URL中各段动态路径也按某种结构对应嵌套的各层组件。
- 创建List.vue
- 配置路由,router.js
{
path: '/',
component: Home,
children: [{ path: '/list', name: 'list', component: List }]
}
- 在Home.vue中添加插座
home
路由守卫
路由导航过程中有若干生命周期钩子,可以在这里实现逻辑控制。
- 全局守卫,router.js
// 守卫
router.beforeEach((to, from, next) => {
// 要访问/about且未登录需要去登录
if (to.meta.auth && !window.isLogin) {
// next('/login')
if (window.confirm("请登录")) {
window.isLogin = true;
next(); // 登录成功,继续
} else {
next('/');// 放弃登录,回首页
}
} else {
next(); // 不需登录,继续
}
});
- 路由独享守卫,home.vue
beforeEnter(to, from, next) {
// 路由内部知道自己需要认证
if (!window.isLogin) {
// ...
} else {
next()
}
}
- 组件内守卫
export default {
beforeRouteEnter(to, from, next) {
//this不能用
},
beforeRouteUpdate(to, from, next) { },
beforeRouteLeave(to, from, next) { }
}
动态路由
// 映射关系
const compMap = {
'home': () => import('./views/Home.vue'),
'about': () => import('./views/About.vue'),
}
// 递归替换
function mapComponent(route) {
route.component = compMap[route.name]
if (route.children) {
route.children = route.children.map(child => mapComponent(child))
}
return route
}
// 异步获取路由
api.getRoutes().then(routes => {
const routeConfig = routes.map(route => mapComponent(route))
router.addRoutes(routeConfig)
})