溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

vue-router2.0跳轉之router.push()的使用方法

發(fā)布時間:2020-08-13 15:51:53 來源:億速云 閱讀:331 作者:小新 欄目:開發(fā)技術

這篇文章主要介紹vue-router2.0跳轉之router.push()的使用方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

router.push(location)

除了使用 創(chuàng)建 a 標簽來定義導航鏈接,我們還可以借助 router 的實例方法,通過編寫代碼來實現。

router.push(location)

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

當你點擊 <router-link> 時,這個方法會在內部調用,所以說,點擊 等同于調用 router.push(…)。

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

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

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

// 字符串
router.push('home')

// 對象
this.$router.push({path: '/login&#63;url=' + this.$route.path});

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

// 帶查詢參數,變成/backend/order&#63;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&#63;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});

replace

類型: boolean

默認值: false

設置 replace 屬性的話,當點擊時,會調用 router.replace() 而不是 router.push(),于是導航后不會留下 history 記錄。即使點擊返回按鈕也不會回到這個頁面。

//加上replace: true后,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄。

this.$router.push({path: '/home', replace: true})
//如果是聲明式就是像下面這樣寫:
<router-link :to="..." replace></router-link>
// 編程式:
router.replace(...)

綜合案例

this.$router.push({path: '/coach/' + this.$route.params.id, query: queryData});

補充知識:解決從登錄頁通過this.$router.push跳轉首頁后 點返回健路由變而頁面不變的問題

做H5項目的時候遇到一個問題,我從 login 登錄頁通過 this.$router.push({ name: 'home' })路由登錄成功后跳轉到首頁,但在ios系統(tǒng)下,會有一個默認返回條,點擊返回鍵出現以下情況,路由顯示的是回到登錄頁,而頁面卻還是首頁。

解決思路:

開始我試著把push改為replace,但是發(fā)現并沒什么卵用,還是會出現問題,所以只好用路由導航守衛(wèi)去監(jiān)聽。

在首頁加入beforeRouteLeave,監(jiān)聽到to.name如果是login的話就不跳轉,否則就跳轉,然后問題就解決了。

beforeRouteLeave (to, from, next) {
  if (to.name === 'login') {
    next(false)// 不跳轉
  } else {
    next() // 跳轉到另一個路由
  }
}

vue-router2.0跳轉之router.push()的使用方法

以上是vue-router2.0跳轉之router.push()的使用方法的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI