vue-router 2.0 常用基礎知識點之router.push(),router.replace(),router.go()


1.router.push(location)=====window.history.pushState

http://www.jianshu.com/p/ee7ff3d1d93d

除了使用 <router-link> 創建 a 標簽來定義導航鏈接,我們還可以借助 router 的實例方法,通過編寫代碼來實現。
router.push(location)
想要導航到不同的 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"}});
// 帶查詢參數,變成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
// 設置查詢參數
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});

2.router.replace(location)=====window.history.replaceState

類型: boolean
默認值: false
設置 replace 屬性的話,當點擊時,會調用 router.replace() 而不是 router.push(),於是導航后不會留下 history 記錄。即使點擊返回按鈕也不會回到這個頁面。
//加上replace: true后,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄。

//跟 router.push 很像,唯一的不同就是,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄

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

3.router.go(n)====window.history.go

1
2
3
4
5
6
7
8
9
10
11
12
// 在瀏覽器記錄中前進一步,等同於 history.forward()
router.go(1)
 
// 后退一步記錄,等同於 history.back()
router.go(-1)
 
// 前進 3 步記錄
router.go(3)
 
// 如果 history 記錄不夠用,那就默默地失敗唄
router.go(-100)
router.go(100)

綜合案例

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM