場(chǎng)景:A頁面跳轉(zhuǎn)到B頁面并攜帶參數(shù)
方案一:聲明式導(dǎo)航router-link
1.1不帶參數(shù):
// 注意:router-link中鏈接如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當(dāng)前路由開始暂筝。
<router-link :to="{name:'home'}">
<router-link :to="{path:'/home'}"> //name,path都行, 建議用name
1.2帶參數(shù):
<router-link :to="{name:'home', params: {id:1}}">
<router-link :to="{name:'home', query: {id:1}}">
<router-link :to="/home/:id">
//傳遞對(duì)象
<router-link :to="{name:'detail', query: {item:JSON.stringify(obj)}}"></router-link>
方案二:編程式導(dǎo)航 this.$router.push()
2.1不帶參數(shù):
this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
2.2 query傳參
1.路由配置:
name: 'home',
path: '/home'
2.跳轉(zhuǎn):
this.$router.push({name:'home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
3.獲取參數(shù)
html取參: $route.query.id
script取參: this.$route.query.id
2.3 params傳參
1.路由配置:
name: 'home',
path: '/home/:id'(或者path: '/home:id')
2.跳轉(zhuǎn):
this.$router.push({name:'home',params: {id:'1'}})
注意:
// 只能用 name匹配路由不能用path
// params傳參數(shù)(類似post) 路由配置 path: "/home/:id" 或者 path: "/home:id"否則刷新參數(shù)消失
3.獲取參數(shù)
html取參:$route.params.id
script取參:this.$route.params.id
2.4 直接通過path傳參
1.路由配置:
name: 'home',
path: '/home/:id'
2.跳轉(zhuǎn):
this.$router.push({path:'/home/123'})
或者:
this.$router.push('/home/123')
3.獲取參數(shù):
this.$route.params.id
2.5 傳遞對(duì)象(obj不能過長否則會(huì)報(bào)錯(cuò))
query傳遞對(duì)象 (類似get,url后面會(huì)顯示參數(shù)) JSON.stringify(obj) 轉(zhuǎn)一下.
接收參數(shù):
JS:JSON.parse(decodeURIComponent(this.$route.query.obj))
HTML:JSON.parse(decodeURIComponent($route.query.obj))
2.6 params和query的區(qū)別
query類似 get呐芥,跳轉(zhuǎn)之后頁面 url后面會(huì)拼接參數(shù)晶衷,類似?id=1你虹。
非重要性的可以這樣傳抛杨,密碼之類還是用params暗赶,刷新頁面id還在鄙币。
params類似 post,跳轉(zhuǎn)之后頁面 url后面不會(huì)拼接參數(shù)蹂随。
方案三.this.$router.replace()
用法同上:this.$router.push()
方案四this.$router.go(n)
向前或者向后跳轉(zhuǎn)n個(gè)頁面爱榔,n可為正整數(shù)或負(fù)整數(shù)
區(qū)別:
1.this.$router.push
跳轉(zhuǎn)到指定url路徑,并在history棧中添加一個(gè)記錄糙及,點(diǎn)擊后退會(huì)返回到上一個(gè)頁面
-
this.$router.replace
跳轉(zhuǎn)到指定url路徑详幽,但是history棧中不會(huì)有記錄,點(diǎn)擊返回會(huì)跳轉(zhuǎn)到上上個(gè)頁面 (就是直接替換了當(dāng)前頁面)
3.this.$router.go(n)
向前或者向后跳轉(zhuǎn)n個(gè)頁面浸锨,n可為正整數(shù)或負(fù)整數(shù)
總結(jié):
1.query
可以用name
和path
匹配路由唇聘,通過this.$route.query.id
獲取參數(shù),刷新瀏覽器參數(shù)不會(huì)丟失
2.params
只能用name
匹配路由柱搜,通過path
匹配路由獲取不到參數(shù)迟郎,對(duì)應(yīng)的路由配置path:'/home/:id'
或者path:'home:id'
,否則刷新瀏覽器參數(shù)丟失
3.直接通過url傳參聪蘸,push({path: '/home/123'})
或者push('/home/123')
宪肖,對(duì)應(yīng)的路由配置path:'/home/:id'
表制,刷新瀏覽器參數(shù)不會(huì)丟失