vue this.$router 和 this.$route 的理解和使用


理解

官方文檔說明如下:

通過注入路由,我們可以在任何組件內通過 this.$router 訪問路由器,也可以通過 this.$route 訪問當前的路由。

注入路由,在 mian.js 中引入 路由,並且注入。

import router from './router';
new Vue({
  el: '#app',
  router,
  ...
  mounted() { }
})

可以理解為:

  • this.$router 相當於一個全局的路由對象,包含路由相關的屬性、對象 (如 history 對象) 和方法,在任何頁面都可以通過 this.$router 調用其方法如 push()go()resolve() 等。
  • this.$route 表示當前的路由對象。每一個路由都有一個 route 對象,它是一個局部的對象,可以獲取當前路由對應的 name , params, path , query 等屬性。

this.$router 等同於 router。在 main.js 中,我們直接引入了 router 則可以使用類似這樣的方式 router.push() 調用相關屬性或者方法。

使用: 以 push() 方法為例

在 vue 項目開發中, 我們通常使用 router.push() 實現頁面間的跳轉,稱為編程式導航。這個方法會向 history 棧中添加一個歷史記錄,但用戶點擊瀏覽器的后退按鈕時,就會回到之前的 URL。

當我們點擊 時,會在內部調用 router.push() 方法。

push方法調用:

//字符串  
this.$router.push('home') //->/home

//對象
this.$router.push({path:'home'}) //->/home

//命名的路由
this.$router.push({name:'user', params:{userId: '123'}}) //->/user/123

//帶查詢參數,變成 /register?plan=private
this.$router.push({path:'register', query:{plan:private}}) 

const userId = '123';
//這里的 params 不生效
this.$router.push({path:'/user', params:{userId}});  //->/user

params 傳參,push 里面只能是 name: 'xxx', 不能是 path: 'xxx',因為 params 只能用 name 來引入路由,如果這里寫成了 path ,接收參數頁面會是 undefined。

路由傳參的方式:

1、手寫完整的 path:
 
    this.$router.push({path: `/user/${userId}`});
 
    獲取參數:this.$route.params.userId
 
2、用 params 傳遞:
 
    this.$router.push({name:'user', params:{userId: '123'}});
 
    獲取參數:this.$route.params.userId
 
    url 形式:url 不帶參數,http:localhost:8080/#/user
 
3、用 query 傳遞:
 
    this.$router.push({path:'/user', query:{userId: '123'}});
 
    獲取參數:this.$route.query.userId
 
    url 形式:url 帶參數,http:localhost:8080/#/user?userId=123

直白的說,query 相當於 get 請求,頁面跳轉的時候可以在地址欄看到請求參數,params 相當於 post 請求,參數不在地址欄中顯示。

要注意,以 / 開頭的嵌套路徑會被當作根路徑。 這讓你充分的使用嵌套組件而無須設置嵌套的路徑。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM