vue-router 2.0 常用基礎知識點之router.push()
前言
本文作為記錄,原文轉自這裡,針對小部分內容整改加入了自己的理解
router.push(location)
除了使用<router-link>
建立a
標籤來定義導航連結,我們還可以藉助router
的例項方法,通過編寫程式碼來實現,案例如下
router.push(location)
想要導航到不同的 URL,則使用router.push
方法。這個方法會向history
棧新增一個新的記錄,所以,當用戶點選瀏覽器後退按鈕時,則回到之前的 URL。
在一個帶有<router-link>
的template
中,當用戶點選該連結,實質上是在內部呼叫了router.push()
方法,因此,顯示呼叫router.push(...)
實質上與<router-link :to="...">
是一致的,只不過一個是標籤用法,一個是腳邏輯用法
宣告式:<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 關鍵字
設定replace
屬性的話,當點選時,會呼叫router.replace()
而不是router.push()
,於是導航後不會留下history
記錄。即使點選返回按鈕也不會回到這個頁面。它所執行的是替換掉當前路由的歷史記錄
- 型別: boolean
- 預設值: false
this.$router.push({path: '/home', replace: true}) //如果是宣告式就是像下面這樣寫: <router-link :to="..." replace></router-link> // 程式設計式: router.replace(...)
綜合案例
let queryData = { id: this.groupID, name: this.groupName, tags: 30 } this.$router.push({path: '/coach/' + this.$route.params.id, query: queryData});