vue中this.$router.push()路由傳值和獲取的兩種常見方法


1、路由傳值   this.$router.push()

(1) 想要導航到不同的URL,使用router.push()方法,這個方法會向history棧添加一個新紀錄,所以,當用戶點擊瀏覽器后退按鈕時,會回到之前的URL

(2)當點擊 <router-link> 時,這個方法會在內部調用,即點擊 <router-link :to="..."> 等同於調用 router.push(...)

  a)      聲明式:<router-link :to="...">

  b)      編程式:router.push(...)

  c)      該方法的參數可以是一個字符串路徑,或者一個描述地址的對象。 

// 字符串
router.push('home')
 
// 對象
this.$router.push({path: '/login?url=' + this.$route.path});
 
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
 
// 帶查詢參數,變成/backend/order?selected=2
this.$router.push({path: '/backend/order', query: {selected: "2"}});
 
// 設置查詢參數
this.$http.post('v1/user/select-stage', {stage: stage})
      .then(({data: {code, content}}) => {
            if (code === 0) {
                // 對象
                this.$router.push({path: '/home'});
            }else if(code === 10){
                // 帶查詢參數,變成/login?stage=stage
                this.$router.push({path: '/login', query:{stage: stage}});
           }
});
 
// 設計查詢參數對象
let queryData = {};
if (this.$route.query.stage) {
    queryData.stage = this.$route.query.stage;
}
if (this.$route.query.url) {
    queryData.url = this.$route.query.url;
}
this.$router.push({path: '/my/profile', query: queryData});

 

 

2、獲取參數的兩種常用方法:params和query

(1)由於動態路由也是傳遞params的,所以在 this.$router.push() 方法中path不能和params一起使用,否則params將無效。需要用name來指定頁面。

及通過路由配置的name屬性訪問

 

 

 

 

this.$router.push({name:"menuLink",params:{alert:"頁面跳轉成功"}})

(2)在目標頁面通過this.$route.params獲取參數:

<p>提示:{{this.$route.params.alert}}</p>

(3)在目標頁面通過this.$route.query 獲取參數

 
//傳值
this.$router.push({path:"/menLink",query:{alert:"頁面跳轉成功"}})

//用query獲取值
<p>提示:{{this.$route.query.alert}}</p>
兩種方式的區別是query傳參的參數會帶在url后邊展示在地址欄,params傳參的參數不會展示到地址欄。
需要注意的是接收參數的時候是route而不是router。兩種方式一一對應,名字不能混用
 
 


免責聲明!

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



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