詳解vue 路由跳轉(zhuǎn)四種方式 (帶參數(shù))

  1. router-link
1. 不帶參數(shù)
 <router-link :to="{name:'home'}"> 
<router-link :to="{path:'/home'}"> //name,path都行, 建議用name 
// 注意:router-link中鏈接如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當(dāng)前路由開始。
 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() (函數(shù)里面調(diào)用)
1. 不帶參數(shù)
 this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
2. query傳參 
 this.$router.push({name:'home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
// html 取參 $route.query.id
// script 取參 this.$route.query.id
3. params傳參
 this.$router.push({name:'home',params: {id:'1'}}) // 只能用 name
  
// 路由配置 path: "/home/:id" 或者 path: "/home:id" ,
// 不配置path ,第一次可請求,刷新頁面id會消失
// 配置path,刷新頁面id會保留
// html 取參 $route.params.id
// script 取參 this.$route.params.id
4. query和params區(qū)別
query類似 get, 跳轉(zhuǎn)之后頁面 url后面會拼接參數(shù),類似?id=1, 非重要性的可以這樣傳, 密碼之類還是用params刷新頁面id還在
 params類似 post, 跳轉(zhuǎn)之后頁面 url后面不會拼接參數(shù) , 但是刷新頁面id 會消失
  1. this.$router.replace() (用法同上,push)

  2. this.$router.go(n) ()

this.$router.go(n)

向前或者向后跳轉(zhuǎn)n個頁面,n可為正整數(shù)或負(fù)整數(shù)

ps : 區(qū)別

this.$router.push

跳轉(zhuǎn)到指定url路徑,并想history棧中添加一個記錄,點擊后退會返回到上一個頁面

this.$router.replace

跳轉(zhuǎn)到指定url路徑,但是history棧中不會有記錄,點擊返回會跳轉(zhuǎn)到上上個頁面 (就是直接替換了當(dāng)前頁面)

this.$router.go(n)

向前或者向后跳轉(zhuǎn)n個頁面,n可為正整數(shù)或負(fù)整數(shù)

Vue如何獲取當(dāng)前頁面的url,獲取路由地址

完整url可以用 window.location.href
路由路徑可以用 this.$route.path
路由路徑參數(shù) this.$route.params 例如:/user/:id → /user/2044011030 → this.$route.params.id
路由查詢參數(shù) this.$route.query 例如:/user/search?name=sf → this.$route.query.name

參考:https://www.cnblogs.com/bydzhangxiaowei/p/12000458.html
https://blog.csdn.net/a350110085/article/details/90053111

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容