路由懶加載
實(shí)際項(xiàng)目中使用
const router = new Router({
routes: [
{
path: '/', //主頁
component: () => import('@/pages/Index/template.vue')
},
{
path:'/login', //登錄頁面
component: () => import('@/pages/Login/template.vue')
},
{
path:'/create', //創(chuàng)建博客頁面
component: () => import('@/pages/Create/template.vue'),
meta:{requireAuth: true}
},
{
path:'/detail/:blogId', //博客詳情頁面
component: () => import('@/pages/Detail/template.vue')
},
{
path:'/edit/:blogId', //編輯,修改博客頁面
component: () => import('@/pages/Edit/template.vue'),
meta:{requireAuth: true}
},
{
path:'/my', //我的頁面
component: () => import('@/pages/My/template.vue'),
meta:{requireAuth: true}
},
{
path:'/register', //注冊頁面
component: () => import('@/pages/Register/template.vue')
},
{
path:'/user/:userId', //用戶他人頁面
component: () => import('@/pages/User/template.vue')
}
]
})
當(dāng)打包構(gòu)建應(yīng)用時(shí),JavaScript 包會變得非常大,影響頁面加載。如果我們能把不同路由對應(yīng)的組件分割成不同的代碼塊,然后當(dāng)路由被訪問的時(shí)候才加載對應(yīng)組件,這樣就更加高效了。
結(jié)合 Vue 的異步組件和 Webpack 的代碼分割功能,輕松實(shí)現(xiàn)路由組件的懶加載。
首先,可以將異步組件定義為返回一個(gè) Promise 的工廠函數(shù) (該函數(shù)返回的 Promise 應(yīng)該 resolve 組件本身):
const Foo = () => Promise.resolve({ /* 組件定義對象 */ })
第二,在 Webpack 2 中,我們可以使用動態(tài) import語法來定義代碼分塊點(diǎn) (split point):
import('./Foo.vue') // 返回 Promise
結(jié)合這兩者,這就是如何定義一個(gè)能夠被 Webpack 自動代碼分割的異步組件。
const Foo = () => import('./Foo.vue')
在路由中使用:
const router = new VueRouter({
routes: [
{ path: '/foo', component: Foo }
]
})
路由對象
一個(gè)路由對象 (route object) 表示當(dāng)前激活的路由的狀態(tài)信息,包含了當(dāng)前 URL 解析得到的信息,還有 URL 匹配到的路由記錄 (route records)。
路由對象是不可變 (immutable) 的,每次成功的導(dǎo)航后都會產(chǎn)生一個(gè)新的對象。
- 在組件內(nèi),即 this.$route
- 導(dǎo)航守衛(wèi)的參數(shù):
router.beforeEach((to, from, next) => {
// `to` 和 `from` 都是路由對象
})
路由對象屬性
- $route.path
- $route.params
- $route.query
- $route.hash
- $route.fullPath
完成解析后的 URL,包含查詢參數(shù)和 hash 的完整路徑。 - $route.matched
一個(gè)數(shù)組,包含當(dāng)前路由的所有嵌套路徑片段的路由記錄 。路由記錄就是 routes 配置數(shù)組中的對象副本 (還有在 children 數(shù)組)。
路由注入
通過在 Vue 根實(shí)例的 router 配置傳入 router 實(shí)例,下面這些屬性成員會被注入到每個(gè)子組件。
- this.$router
router實(shí)例 - this.$route
當(dāng)前激活的路由信息對象。這個(gè)屬性是只讀的,里面的屬性是 immutable (不可變) 的,不過你可以 watch (監(jiān)測變化) 它。
動態(tài)路由
例如,我們有一個(gè) User 組件,對于所有 ID 各不相同的用戶,都要使用這個(gè)組件來渲染。那么,我們可以在 vue-router 的路由路徑中使用“動態(tài)路徑參數(shù)”(dynamic segment) 來達(dá)到這個(gè)效果:
const User = {
template: '<div>User</div>'
}
const router = new VueRouter({
routes: [
// 動態(tài)路徑參數(shù) 以冒號開頭
{ path: '/user/:id', component: User }
]
})
一個(gè)“路徑參數(shù)”使用冒號 : 標(biāo)記。當(dāng)匹配到一個(gè)路由時(shí),參數(shù)值會被設(shè)置到 this.$route.params,可以在每個(gè)組件內(nèi)使用。
路由守衛(wèi)
vue-router 提供的導(dǎo)航守衛(wèi)主要用來通過跳轉(zhuǎn)或取消的方式守衛(wèi)導(dǎo)航。有多種機(jī)會植入路由導(dǎo)航過程中:全局的, 單個(gè)路由獨(dú)享的, 或者組件級的。
記住參數(shù)或查詢的改變并不會觸發(fā)進(jìn)入/離開的導(dǎo)航守衛(wèi)。你可以通過觀察 $route 對象來應(yīng)對這些變化,或使用 beforeRouteUpdate 的組件內(nèi)守衛(wèi)。
全局前置守衛(wèi)
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})