1. 程式人生 > 程式設計 >vue-router 2.0 跳轉之router.push()用法說明

vue-router 2.0 跳轉之router.push()用法說明

router.push(location)

除了使用 建立 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?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});

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系統下,會有一個預設返回條,點選返回鍵出現以下情況,路由顯示的是回到登入頁,而頁面卻還是首頁。

解決思路:

開始我試著把push改為replace,但是發現並沒什麼卵用,還是會出現問題,所以只好用路由導航守衛去監聽。

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

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

vue-router 2.0 跳轉之router.push()用法說明

以上這篇vue-router 2.0 跳轉之router.push()用法說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。