說明
- vue路由,即
vue-router
- 中文文檔
- 安裝:
npm install vue-router --save
- 所謂的路由就是一個
key-value
的映射關係,在vue路由中key指的是組件的 path
,value指的是組件
。
相關API說明
VueRouter()
用於創建路由器的構造函數。new VueRouter({ // 多個配置項 });
- 路由配置
routes:[ { // 一般路由 path:'/about', component:About }, { //自動跳轉路由 path:'/', redirect:'/about', } ];
- 掛載路由器
import router from './router'; new Vue({ router, });
- 使用路由組件標籤
<router-link>
:用來生成路由鏈接- 用法:
<router-link to="/xxx">Go to xxx </router-link>
<router-link>
和<a>
標籤十分類似,to 屬性和<a>
標籤的 href 屬性十分類似。
- 用法:
<router-view>
: 用來顯示當前路由組件的界面- 用法:
<router-view></router-view>
<router-view>
的作用十分類似 vue 中的插槽(slot)
- 用法:
- 注意:
- path 最左側的
/
永遠代表根路徑。 - 優化路由器配置:
linkActiveClass: 'active', // 指定選中的路由鏈接的 class
- path 最左側的
編寫路由的步驟
- 創建路由組件
- 將路由組件映射成路由關係
- 通過
<router-link>
和<router-view>
使用路由組件
嵌套路由
- 在要嵌套的父路由配置中 使用
children
關鍵字定義子路由配置 - 子路由的配置和
routes
的配置一樣。
緩存路由組件對象
- 默認情況下,被切換的路由組件對象會死亡釋放,再次回來時是重新創建的。
- 當數據實時性低的時候,如果可以緩存路由組件對象,可以提高用戶體驗
- 編碼實現:
<keep-alive> <router-view></router-view> </keep-alive>
向路由組件傳遞數據
方式1:路由路徑攜帶參數(Param/query)
- 配置路由:
children:[ { path:'mdetail/:id', component:MessageDetail } ]
- 路由路徑
<router-link :to="'/home/message/mdetail/'+m.id"> {{m.title}} </router-link>
- 路由組件中讀取請求參數
this.$route.params.id
方式2:<router-view>
屬性攜帶數據
<router-view :msg="msg"></router-view>
編程式路由導航
相關API
this.$router.push(path)
:相當於點擊路由鏈接(可以返回當前路由界面)this.$router.replace(path)
: 用新路由替換當前路由(不可以返回到當前路由)this.$router.back()
: 請求(返回)上一個記錄路由this.$router.go(-1)
: 請求(返回)上一個記錄路由this.$router.go(-1)
: 請求下一個記錄路由
路由導航守衛
- 導航:表示路由正在發生改變
- 路由導航守衛表示監視路由的改變,然後在改變的過程中進行一些操作
- 路由的
參數或查詢的改變不會觸發進入/離開導航守衛
,可以通過 監視$route
對象來應對這些變化
全局前置守衛
- 通過
router.beforeEach
註冊const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
- 參數分析:
- to:將要前往的路由
- from: 將要離開的當前路由
- next(): 進入路由
- 一定要調用該方法,否則路由會一直掛起
- next():進入將要前往的路由
- next(path): 進入指定path的路由
- 參考下面的代碼:
// 設置路由導航守衛 router.beforeEach((to, from, next) => { // console.log(to); // console.log(from); // 要前往的頁面是否是登錄或註冊頁面 if (to.path === '/login' || to.path === '/register') { next(); return; } // 是否登錄 const isLogin = tools.storage.get('token').length !== 0; if (isLogin) { next(); } else { next('/login'); } });