Vue路由跳轉方式區(qū)別匯總(push,replace,go)
在瀏覽器中,點擊鏈接實現導航的方式,叫做聲明式導航。例如:普通網頁中點擊 a標簽鏈接。vue項目中點擊router-link標簽鏈接都屬于聲明式導航。
在瀏覽器中,調用API方法實現導航的方式,叫做編程式導航。例如:普通網頁中調用location.href跳轉到新頁面的方式,屬于編程式導航。vue項目中編程式導航有this.$router.push(),this.$router.replace(),this.$router.go()。
聲明式導航router-link
1. 不帶參數
<router-link :to="{name:'home'}">
<router-link :to="{path:'/home'}">
// name,path都行, 建議用name
// 注意:router-link中鏈接如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當前路由開始。
2.帶參數
<router-link :to="{name:'home', params: {id:1}}">
// params傳參數 (類似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傳參數 (類似get,url后面會顯示參數)
// 路由可不配置
// 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'})
// 帶參數
this.$router.push({path: 'login-pw', query: {'account': this.account.account}})
// 跳轉后的頁面獲取參數
this.account.account = this.$route.query.account2、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可為正整數或負整數
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可為正整數或負整數
到此這篇關于Vue路由跳轉方式區(qū)別匯總(push,replace,go)的文章就介紹到這了,更多相關Vue路由跳轉push,replace,go內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
el-date-picker日期時間選擇器的選擇時間限制到分鐘級別
文章介紹了如何使用el-date-picker 組件來限制用戶選擇的時間,禁止選擇當前時間的日期及時分,同時允許選擇其他日期的全天時分,通過設置 `pickerOptions` 對象的屬性,可以實現對日期和時間的精確控制,感興趣的朋友跟隨小編一起看看吧2025-01-01
vue watch偵聽器有無immediate的運行順序問題
這篇文章主要介紹了vue watch偵聽器有無immediate的運行順序問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

