1. 程式人生 > >vue.js中router.push跳轉頁面、帶引數、設定引數的方法

vue.js中router.push跳轉頁面、帶引數、設定引數的方法

router.push(location)

vue.js中想要跳轉到不同的 URL,需要使用 router.push 方法。

這個方法會向 history 棧新增一個新的記錄,當用戶點選瀏覽器後退按鈕時,則回到之前的 URL。

當你點選 <router-link> 時,這個方法會在內部呼叫,所以說,點選 <router-link :to="..."> 等同於呼叫 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});

文章轉載來自:http://www.sunfengxiang.com/1092.html