Vue路由跳转的4种方式

目录

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

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

4、this.$router.go(n)

         5、this.$router.push()、this.$router.replace()、this.$router.go(n)区别


router-view 实现路由内容的地方,引入组件时写到需要引入的地方,需要注意的是,使用vue-router控制路由则必须router-view作为容器。

通过路由跳转的种四方式

注意: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可为正整数或负整数

5、this.$router.push()、this.$router.replace()、this.$router.go(n)区别

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

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

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

猜你喜欢

转载自blog.csdn.net/m0_64346035/article/details/125177854
今日推荐