場景:A頁面跳轉到B頁面並攜帶參數
方案一:聲明式導航router-link
1.1不帶參數:
1 // 注意:router-link中鏈接如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當前路由開始。 2 <router-link :to="{name:'home'}"> 3 <router-link :to="{path:'/home'}"> //name,path都行, 建議用name
1.2帶參數:
<router-link :to="{name:'home', params: {id:1}}"> <router-link :to="{name:'home', query: {id:1}}"> <router-link :to="/home/:id"> //傳遞對象 <router-link :to="{name:'detail', query: {item:JSON.stringify(obj)}}"></router-link>
方案二:編程式導航 this.$router.push()
2.1不帶參數:
this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
2.2 query傳參
1 1.路由配置: 2 name: 'home', 3 path: '/home' 4 2.跳轉: 5 this.$router.push({name:'home',query: {id:'1'}}) 6 this.$router.push({path:'/home',query: {id:'1'}}) 7 3.獲取參數 8 html取參: $route.query.id 9 script取參: this.$route.query.id
2.3 params傳參
1 1.路由配置: 2 name: 'home', 3 path: '/home/:id'(或者path: '/home:id') 4 2.跳轉: 5 this.$router.push({name:'home',params: {id:'1'}}) 6 注意: 7 // 只能用 name匹配路由不能用path 8 // params傳參數(類似post) 路由配置 path: "/home/:id" 或者 path: "/home:id"否則刷新參數消失 9 3.獲取參數 10 html取參:$route.params.id 11 script取參:this.$route.params.id
2.4 直接通過path傳參
1 1.路由配置: 2 name: 'home', 3 path: '/home/:id' 4 2.跳轉: 5 this.$router.push({path:'/home/123'}) 6 或者: 7 this.$router.push('/home/123') 8 3.獲取參數: 9 this.$route.params.id
2.5 傳遞對象(obj不能過長否則會報錯)
1 query傳遞對象 (類似get,url后面會顯示參數) JSON.stringify(obj) 轉一下. 2 接收參數: 3 JS:JSON.parse(decodeURIComponent(this.$route.query.obj)) 4 HTML:JSON.parse(decodeURIComponent($route.query.obj))
2.6 params和query的區別
query類似 get,跳轉之后頁面 url后面會拼接參數,類似?id=1。
非重要性的可以這樣傳,密碼之類還是用params,刷新頁面id還在。
params類似 post,跳轉之后頁面 url后面不會拼接參數。
方案三.this.$router.replace()
用法同上:this.$router.push()
方案四this.$router.go(n)
向前或者向后跳轉n個頁面,n可為正整數或負整數
區別:
1.this.$router.push
跳轉到指定url路徑,並在history棧中添加一個記錄,點擊后退會返回到上一個頁面
2.this.$router,replace
跳轉到指定url路徑,但是history棧中不會有記錄,點擊返回會跳轉到上上個頁面 (就是直接替換了當前頁面)
3.this.$router.go(n)
向前或者向后跳轉n個頁面,n可為正整數或負整數
總結:
1.query可以用name和path匹配路由,通過this.$route.query.id獲取參數,刷新瀏覽器參數不會丟失
2.params只能用name匹配路由,通過path匹配路由獲取不到參數,對應的路由配置path:'/home/:id'或者path:'home:id',否則刷新瀏覽器參數丟失
3.直接通過url傳參,push({path: '/home/123'})或者push('/home/123'),對應的路由配置path:'/home/:id',刷新瀏覽器參數不會丟失
