路由跳轉的幾種方式
寫的太棒了 https://blog.csdn.net/jiandan1127/article/details/86170336
1. 聲明式跳轉 直接跳轉 包裹內容
//不帶參數跳轉
//(一)
<router-link :to="{name:''}">
查看
</router-link>
//(二)
<router-link :to="{path:'/home'}">
查看
</router-link>
//name,path都行, 建議用name
// 注意:router-link中鏈接如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當前路由開始。
// target="_blank" 用來跳轉到新頁面
//攜帶參數跳轉
//(一)
<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
要是打開新窗口 直接在router-link里面寫此屬性
target="_blank"
2.在方法里面跳轉頁面
1. 不帶參數
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. 打開新窗口
在vue中使用 this.$router.push({ path: '/home' }) 默認是替代本窗口
如果想新開一個窗口,可以使用下面的方式:
let routeData = this.$router.resolve({ path: '/home', query: { id: 1 } });
window.open(routeData.href, '_blank');
query和params區別
query類似 get, 跳轉之后頁面 url后面會拼接參數,類似?id=1, 非重要性的可以這樣傳, 密碼之類還是用params刷新頁面id還在
params類似 post, 跳轉之后頁面 url后面不會拼接參數 , 但是刷新頁面id 會消失
3. this.$router.replace() (用法同上,push)
4. this.$router.go(n)
this.$router.go(n)
向前或者向后跳轉n個頁面,n可為正整數或負整數
**區別**
this.$router.push
跳轉到指定url路徑,並想history棧中添加一個記錄,點擊后退會返回到上一個頁面
this.$router.replace
跳轉到指定url路徑,但是history棧中不會有記錄,點擊返回會跳轉到上上個頁面 (就是直接替換了當前頁面)
this.$router.go(n)
向前或者向后跳轉n個頁面,n可為正整數或負整數