1. 程式人生 > 實用技巧 >vue 中 $route 和 $router 的區別

vue 中 $route 和 $router 的區別

前言:在路由動態載入的時候常需要用到 router 和 route ,記下區分

https://router.vuejs.org/zh/api/#router-%E6%9E%84%E5%BB%BA%E9%80%89%E9%A1%B9

this.$router

是 router 例項,通過 this.$router 訪問路由器,相當是獲得了整個路由檔案。在 $router.option.routes 中,或檢視到當前專案的整個路由結構具有例項方法:

導航守衛
router.beforeEach((to, from, next) => {
    // 必須呼叫next
})
router.beforeResolve((to, from, next) 
=> { /* 必須呼叫 `next` */ }) router.afterEach((to, from) => {}) 動態導航到新路由 router.push router.replace router.go router.back router.forward

this.$route

一個路由物件 (route object)表示當前啟用的路由的狀態資訊,包含了當前 URL 解析得到的資訊,還有 URL 匹配到的路由記錄 (route records)。

路由物件是不可變 (immutable) 的,每次成功的導航後都會產生一個新的物件。不過可以 watch (監測變化) 它。

路由物件出現在多個地方:

  • 在元件內,this.$route
  • 在 $route 觀察者回調內
  • router.match(location) 返回值
  • 導航守衛的引數。 to,from等

通過 this.$route 訪問的是當前路由,獲取和當前路由有關的資訊(例如做動態標籤導航欄)

fullPath: ""  // 當前路由完整路徑,包含查詢引數和 hash 的完整路徑
hash: "" // 當前路由的 hash 值 (錨點)
matched: [] // 包含當前路由的所有巢狀路徑片段的路由記錄 
meta: {} // 路由檔案中自賦值的meta資訊
name: "" // 路由名稱
params: {}  //
一個 key/value 物件,包含了動態片段和全匹配片段就是一個空物件。 path: "" // 字串,對應當前路由的路徑 query: {} // 一個 key/value 物件,表示 URL 查詢引數。跟隨在路徑後用'?'帶的引數