轉載: https://www.cnblogs.com/lwwen/p/7245083.html
https://blog.csdn.net/qq_15385627/article/details/83146766
1.router.push(location)=====window.history.pushState
想要導航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。
// 字符串 router.push('home') // 對象 router.push({ path: 'home' }) // 命名的路由 router.push({ name: 'user', params: { userId: 123 }}) // 帶查詢參數,變成 /register?plan=private router.push({ path: 'register', query: { plan: 'private' }})
2.router.replace(location)=====window.history.replaceState
跟 router.push 很像,唯一的不同就是,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄
3.router.go(n)====window.history.go
// 在瀏覽器記錄中前進一步,等同於 history.forward() router.go(1) // 后退一步記錄,等同於 history.back() router.go(-1) // 前進 3 步記錄 router.go(3) // 如果 history 記錄不夠用,那就默默地失敗唄 router.go(-100) router.go(100)
附:----------------------------
vue.router中replace需要返回兩次問題及解決方案
- 問題:現有三個頁面a , b , c , 遞進關系,a頁面router.push跳轉至b,b再router.push跳轉至c,c使用$router.replace()回到b,然后點擊b頁面的返回鍵,需要點擊兩次才能回到a頁面
- 需求:c保持router.replace至b方式不變,b頁面返回鍵點擊一次正常返回a頁面
- 解決方法:使用replace方法之后,再使用router.go(-1)方法返回一次就可以。
例:
this.router.replacePage({name:'b'}) this.router.go(-1)
- 原理:先解析一下幾種頁面跳轉方式的不同,
- router.push : 跳轉到新的頁面,向history棧添加新一個新紀錄,點擊返回,返回到上一級頁面。
- router.replace: 打開新的頁面,不會像history添加新紀錄,而是直接替換掉當前記錄。
- router.go: 在history有記錄的情況下,前進后退相應的頁面。
頁面的跳轉記錄就是:a->b->c->b
頁面的堆棧記錄則是:a->b->b
那么返回的時候路線就是b->b->a,相當於b頁面有兩個,但由於b頁面是一模一樣的,所以視覺上是覺得點了兩次返回鍵。
那么解決的思路就很清晰了,減少history中的b的記錄,就是在用b替換c頁面記錄同時,回退一頁,記錄就變成a->b,返回的時候自然是直接回到a。
