Vue路由跳轉方式區(qū)別匯總(push,replace,go)
在瀏覽器中,點擊鏈接實現(xiàn)導航的方式,叫做聲明式導航。例如:普通網頁中點擊 a標簽鏈接。vue項目中點擊router-link標簽鏈接都屬于聲明式導航。
在瀏覽器中,調用API方法實現(xiàn)導航的方式,叫做編程式導航。例如:普通網頁中調用location.href跳轉到新頁面的方式,屬于編程式導航。vue項目中編程式導航有this.$router.push(),this.$router.replace(),this.$router.go()。
聲明式導航router-link
1. 不帶參數(shù)
<router-link :to="{name:'home'}"> <router-link :to="{path:'/home'}"> // name,path都行, 建議用name // 注意:router-link中鏈接如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當前路由開始。
2.帶參數(shù)
<router-link :to="{name:'home', params: {id:1}}"> // params傳參數(shù) (類似post) // 路由配置 path: "/home/:id" 或者 path: "/home:id" // 不配置path ,第一次可請求,刷新頁面id會消失 // 配置path,刷新頁面id會保留 // html 取參 $route.params.id // script 取參 this.$route.params.id <router-link :to="{name:'home', query: {id:1}}"> // query傳參數(shù) (類似get,url后面會顯示參數(shù)) // 路由可不配置 // html 取參 $route.query.id // script 取參 this.$route.query.id
編程式導航
1、this.$router.push
跳轉到指定url路徑,并想history棧中添加一個記錄,點擊后退會返回到上一個頁面
在這里插入代碼片// 字符串 this.$router.push('index') // 對象 this.$router.push({path: 'login-pw'}) // 帶參數(shù) this.$router.push({path: 'login-pw', query: {'account': this.account.account}}) // 跳轉后的頁面獲取參數(shù) this.account.account = this.$route.query.account
2、this.$router.replace
1.跳轉到指定的URL,替換history棧中最后一個記錄,點擊后退會返回至上一個頁面。(A----->B----->C 結果B被C替換 A----->C)
2.設置replace屬性(默認值:false)的話,當點擊時,會調用router.replace(),而不是router.push(),于是導航后不會留下history記錄。
3.即使點擊返回按鈕也不會回到這個頁面。加上replace: true時,它不會向 history 添加新紀錄,而是跟它的方法名一樣——替換當前的history記錄。
// 聲明式 <reouter-link :to="..." replace></router-link> // 編程式: router.replace(...) // push方法也可以傳replace this.$router.push({path: '/homo', replace: true})
this.$router.replace({ name: this.pageFrom, params: this.formData })
onConfirm: () => { this.$router.replace('/TravelManage') }
3、this.$router.go(n)
1.向前或者向后跳轉n個頁面,n可為正整數(shù)或負整數(shù)
2.this.$router.go(1) // 類似history.forward()
3.this.$router.go(-1) // 類似history.back()
總結區(qū)別:
this.$router.push
跳轉到指定url路徑,并想history棧中添加一個記錄,點擊后退會返回到上一個頁面
this.$router.replace
跳轉到指定url路徑,但是history棧中不會有記錄,點擊返回會跳轉到上上個頁面 (就是直接替換了當前頁面)
this.$router.go(n)
向前或者向后跳轉n個頁面,n可為正整數(shù)或負整數(shù)
到此這篇關于Vue路由跳轉方式區(qū)別匯總(push,replace,go)的文章就介紹到這了,更多相關Vue路由跳轉push,replace,go內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue-Router實現(xiàn)頁面正在加載特效方法示例
這篇文章主要給大家介紹了利用Vue-Router實現(xiàn)頁面正在加載特效方法示例,文中給出了詳細的示例代碼,相信對大家具有一定的參考價值,有需要的朋友們下面來一起看看吧。2017-02-02