Vue 路由跳转方式

911 阅读1分钟

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。

vue路由跳转四种方式

  1. router-link
  2. this.$router.push() (函数里调用)
  3. this.$router.replace() (用法同push一样)
  4. this.$router.go(x)

声明式导航(router-link)

1. 带参

<router-link  :to="{name:'xxx', params: {id:1}}" />

  • params传参数 (类似post)
  • 在路由配置 path: "/xxx/:id" 或者 path: "/xxx:id"
  • 不配置path ,第一次可请求,刷新页面id会消失
  • 配置path,刷新页面id会保留
  • html 取 $route.params.id
  • script 取 this.$route.params.id

<router-link  :to="{name:'xxx', query: {id:1}}" />

  • query传参数 (类似get,url后面会显示参数)
  • 路由可不配置
  • html 取 $route.query.id
  • script 取 this.$route.query.id

2. 不带参

  • <router-link  :to="{name:xxx}" /> 
  • <router-link  :to="{path:/xxx}" /> //(注:如果是 “/” 开始那就是从根路由开始,否则就是从当前路由开始)

编程式导航(router.push)

1. 带参

query:

  • this.$router.push("{name:'xxx',query:{id:1}}")
  • this.$router.push("{path:'/xxx',query:{id:1}}")

params

  • this.$router.push("{name:'xxx',params:{id:1}}") // (注:path跟query搭配,name跟params搭配。)

query传参和params传参两者的区别

  1. 使用query传参使用path来引入路由。
  2. 在使用params传参时只能用name来引入路由,push里面只能是name:'xxx',不能是path:'/xxx'。因为params只能用在name来引入路由,如果这里写成了path,接收参数页面会undefined。
  3. params类似post属于密传参,参数不会显示到URL地址栏,涉及到隐私的用它较合适。                 
  4. query类似get,所传的参数会显示到URL地址栏,相对来说没安全性。

2. 不带参

  • this.$router.push("xxx") 
  • this.$router.push("{name:'xxx'}")
  • this.$router.push("{path:'/xxx'}")

this.$router.replace() 

//(注:用法请参考上面编程式导航push的用法)

this.$router.go(x)

// 向前或者向后跳转x个页面,x既能为正整数也能为负整数

总结:

this.$router.push 是跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面

this.$router.replace 跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)

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

呜呜呜呜呜呜呜呜呜呜呜呜呜 人与人的悲欢并不相通

呜呜呜.jpg

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!