目錄
介紹
vue-router是vue.js得官方路由管理器。
優點:體驗好,不需要每次從服務器獲取全部,快速得展示給用戶
缺點:瀏覽器每次前進 / 倒退時都需重新發起請求;單頁應用前進 / 倒退時無法記住滾動位置。
使用方法
- npm install vue-router -save
- src 目錄下 新建 router 目錄,目錄下新建 index.js
//index.js import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ ] })
-
main.js中引用
import Vue from 'vue' import App from './App' import router from './router' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
基礎知識
- 路由跳轉方式:<router-link to=""></router-link> 或 this.$router.push("");
- 動態路由匹配,以冒號開頭
import Vue from 'vue' import Router from 'Vue-router' import HelloWorld from './helloWorld' Vue.use(Router) export default new Router ({ routes:[ { //動態路徑參數,以冒號開頭,通過$router獲取id path:'helloWorld/:id', //設置props:true時,可在helloWorld組件中設置props:['id'],直接使用this.id name:'HelloWorld ', component:HelloWorld } ] })
-
編程式導航
router.push('home') ;// 字符串 router.push({path:'home'}); // 對象 router.push({name:'user',params:{userId:123}}); // 命名的路由 router.push({path:'register',query:{plan:'private'}});// 帶查詢參數,變成 /register?plan=private ,獲取this.$route.query.plan
注意哦,如果使用path的時候不能用params傳參,使用params傳參時會被忽略,獲取參數爲undefined。
導航守衛
1.全局導航守衛。
參數:to: Route: 即將要進入的目標 路由對象
from: Route: 當前導航正要離開的路由
next: Function: 一定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數。
router.beforeEach((to,from,next)=>{})//前置守衛
router.beforeReslove((to,from,next)=>{})//解析守衛
router.afterEach((to,from)=>{})//後置守衛
2.路由獨享守衛
獨享守衛在全局導航前置守衛調用後再被調用,所以不會被全局守衛覆蓋。
beforeEnter((to,from,next)=>{})
3.路由組件內獨享守衛
beforeRouteEnter((to,from,next)=>{
//進入路有前
//在路由獨享守衛調用後調用,不!能!獲取組件實例this,組件實例還未被創建。
})
beforeRouteUpdate((to,from,next)=>{
//(2.2) 路由複用同一個組件時
// 在當前路由改變,但是該組件被複用時調用 可以訪問組件實例 `this`
// 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
// 由於會渲染同樣的 Foo 組件,因此組件實例會被複用。而這個鉤子就會在這個情況下被調用。
})
beforeRouteLeave((to,from,next)=>{
//離開當前路由時使用
//可用‘this’
})
Keep-alive
緩存組件內部狀態,避免重新渲染,它自身不會渲染一個dom元素,也不會出現在父組件的鏈中。
屬性:
include:匹配的 路由/組件 會被緩存
exclude:匹配的 路由/組件 不會被緩存
include
和exclude
支持三種方式來有條件的緩存路由:採用逗號分隔的字符串形式,正則形式,數組形式。正則和數組形式時需用 v-bind。exclude的優先級大於include,當兩者同時存在時,include將失效。
緩存組件使用方式:
<!-- 逗號分隔字符串 -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
<!-- 正則表達式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
<!-- 數組 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>
路由中使用keep-alive:
<keep-alive include="a,b">
<router-view></router-view>
</keep-alive>
匹配原則:
- 匹配組件的name選項,如果name選項不可用
- 匹配局部註冊的名稱
- 匿名組件,不可匹配。
- 只能匹配當前被包裹的組件,不能匹配其子組件
- 不會在函數式組件中正常工作,因爲沒有緩存實例