1. 路由組件傳參
頁面組件可以通過props接收url參數
布爾模式
{
path: '/argu/:name',
name: 'argu',
component: () => import('@/views/argu.vue'),
props: true
}
對象模式
{
path: '/about',
name: 'about',
component: () => import('@/views/About.vue'),
props: {
food: 'banana'
}
}
函數模式
{
path: '/search',
component: SearchUser,
props: (route) => ({ query: route.query.q })
}
2. HTML5 History模式
vue-router 默認 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL,例: loccalhost:8080/#/,#就是hash模式
如果不想要很醜的 hash,我們可以用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須重新加載頁面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
當你使用 history 模式時,URL 就像正常的 url,例如 http://yoursite.com/user/id,也好看!
不過這種模式要玩好,還需要後臺配置支持。因爲我們的應用是個單頁客戶端應用,如果後臺沒有正確的配置,當用戶在瀏覽器直接訪問 http://oursite.com/user/id 就會返回 404,這就不好看了。
所以呢,你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是你 app 依賴的頁面。
或者
在 Vue 應用裏面覆蓋所有的路由情況,然後在給出一個 404 頁面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
3. 導航守衛
1.導航被觸發。
2.在失活的組件裏調用離開守衛。
3.調用全局的 beforeEach 守衛。
4.在重用的組件裏調用 beforeRouteUpdate 守衛 (2.2+)。
5.在路由配置裏調用 beforeEnter。
6.解析異步路由組件。
7.在被激活的組件裏調用 beforeRouteEnter。
8.調用全局的 beforeResolve 守衛 (2.5+)。
9.導航被確認。
10.調用全局的 afterEach 鉤子。
11.觸發 DOM 更新。
12.用創建好的實例調用 beforeRouteEnter 守衛中傳給 next 的回調函數。
4. 路由元信息
定義路由的時候可以配置 meta 字段
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
children: [
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
}
]
}
]
})
5. 過渡效果
<template>
<div id="app">
<transition-group name="router">
<router-view key="default"/>
<router-view key="email" name="email"/>
<router-view key="tel" name="tel"/>
</transition-group>
</div>
</template>
<style lang="less">
.router-enter{
opacity: 0;
}
.router-enter-active{
transition: opacity 1s ease;
}
.router-enter-to{
opacity: 1;
}
.router-leave{
opacity: 1;
}
.router-leave-active{
transition: opacity 1s ease;
}
.router-leave-to{
opacity: 0;
}
</style>