Vue路由跳转的几种方式及路由重定向

1. 标签路由 router-link

注意:router-link中,链接如果是’/'开头则表示从根路由开始;如果开头不带‘/’,则从当前路由开始。
(1)不带参数

<router-link :to="{name:'home'}"> 
<router-link :to="{path:'/home'}">

(2)带参数

<router-link :to="{name:'home', params: {id:1}}">  
// params传参数 (类似post)
// 路由配置 path: "/home/:id" 或者 path: "/home:id" 
// 不配置path ,第一次可请求,刷新页面id会消失(比如,点击某件商品图片的“查看详情”,跳转到该商品的详情页面,刚开始进入详情页面时能拿到数据(根据商品id获取),刷新页面后,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

2. 编程式路由 this.$router.push()

(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'}})
// query传参数 (类似get,页面url后面会显示参数)
// 路由可不配置
// html 取参 $route.query.id
// script 取参 this.$route.query.id
  • params传参
this.$router.push({name:'home',params: {id:'1'}})  // 只能用 name
// params传参数
// 路由配置 path: "/home/:id"
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留
// html 取参 $route.params.id
// script 取参 this.$route.params.id

3. this.$router.replace()(与this.$router.push()类似)

4. this.$router.go(n)

this.$router.go(n)
向前或者向后跳转n个页面,n可为正整数或负整数

this.$router.push()、this.$router.replace()、this.$router.go(n)三者之间的区别:

  • this.$router.push():跳转到指定url路径,并向history栈中添加一条记录,点击后退会返回到上一个页面;
  • this.$router.replace():跳转到指定url路径,但是history栈中不会有记录(即直接替换成当前页面),点击返回,跳转到上个页面的前一个页面;
  • this.$router.go(n):向前或向后跳转n个页面,n可为正整数或负整数。

原文链接:
https://blog.csdn.net/jiandan1127/article/details/86170336

猜你喜欢

转载自blog.csdn.net/username666/article/details/106751367
今日推荐