使用
// 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");
路由視圖
<router-view/>
導(dǎo)航鏈接
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
路由嵌套
應(yīng)用界面通常由多層嵌套的組件組合而成。同樣的,URL中各段動態(tài)路徑也按某種結(jié)構(gòu)對應(yīng)嵌套的各層組件。
- 創(chuàng)建List.vue
- 配置路由,router.js
{
path: '/',
component: Home,
children: [{ path: '/list', name: 'list', component: List }]
}
- 在Home.vue中添加插座
<template>
<div class='home'>
<h1>home</h1>
<router-view/>
</div>
</template>
路由守衛(wèi)
路由導(dǎo)航過程中有若干生命周期鉤子,可以在這里實現(xiàn)邏輯控制。
- 全局守衛(wèi),router.js
// 守衛(wèi)
router.beforeEach((to, from, next) => {
// 要訪問/about且未登錄需要去登錄
if (to.meta.auth && !window.isLogin) {
// next('/login')
if (window.confirm("請登錄")) {
window.isLogin = true;
next(); // 登錄成功,繼續(xù)
} else {
next('/');// 放棄登錄,回首頁
}
} else {
next(); // 不需登錄,繼續(xù)
}
});
- 路由獨享守衛(wèi),home.vue
beforeEnter(to, from, next) {
// 路由內(nèi)部知道自己需要認證
if (!window.isLogin) {
// ...
} else {
next()
}
}
- 組件內(nèi)守衛(wèi)
export default {
beforeRouteEnter(to, from, next) {
//this不能用
},
beforeRouteUpdate(to, from, next) { },
beforeRouteLeave(to, from, next) { }
}
動態(tài)路由
// 映射關(guān)系
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)
})