Vue 路由跳转、路由传参、跳转区别、传值取值


版权声明:本文为CSDN博主「灬ManongLai」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39453402/article/details/127958797

1、router-link

<router-link :to="{name:'home'}"> 
<router-link :to="{path:'/home'}">
<router-link :to="{name:'home', params: {id:1}}"> 
// 取参  this.$route.params.id
// 路由配置 path: "/home/:id" 或者 path: "/home:id" 
{ path: '/home/:id', ... }
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留
<router-link :to="{name:'home', query: {id:1}}">
// 取参  this.$route.query.id
// 路由可不配置
// router-link中链接如果是'/'开始就是从根路由开始
// 如果开始不带'/',则从当前路由开始。

2、this.$router.push()

this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
this.$router.push({name:'home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
// 取参 this.$route.query.id
this.$router.push({name:'home',params: {id:'1'}})
// 取参 this.$route.params.id
// path 和 Name路由跳转方式,都可以用query传参
// params传参,push里面只能是 name:'xxx',不能是path:'/xxx'
// 因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined
// query:类似 get, 跳转之后页面 url后面会拼接参数,类似?id=1, 非重要性的可以这样刷新页面id还在;
// params:类似 post, 跳转之后页面 url后面不会拼接参数 , 但是刷新页面id 会消失;

3、this.$router.replace()

// 用法同上,push。以下是示例及特别点
// 声明式
<reouter-link :to="..." replace></router-link>
// 编程式:
router.replace(...)
// push方法也可以传replace
this.$router.push({path: '/homo', replace: true})

// 跳转到指定的URL,替换history栈中最后一个记录
// 点击后退会返回至上一个页面。(A----->B----->C 结果B被C替换 A----->C)

// 设置replace属性(默认值:false)的话,当点击时,会调用router.replace()
// 而不是router.push(),于是导航后不会留下 history记录 。
// 即使点击返回按钮也不会回到这个页面。
// 加上replace: true时,它不会向 history 添加新记录,而是跟它的方法名一样——替换当前的history记录

4、this.$router.go(n)

this.$router.go(n)
// 向前或者向后跳转n个页面,n可为正整数或负整数
// 在浏览器记录中向前进一步,等同于history.forward()
router.go(1)
// 后退一步记录,等同于history.back()
router.go(-1)

5、跳转区别

this.$router.push
//向 history 栈中添加一个记录,点击后退会返回到上一个页面
this.$router.replace
//不向 history 栈中记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)
this.$router.go(n)
// 向前或者向后跳转n个页面,n可为正整数或负整数
posted on 2023-05-09 15:28  大山008  阅读(81)  评论(0编辑  收藏  举报