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});
發佈了34 篇原創文章 · 獲贊 21 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章