Vue中this.$router与this.$route的区别及其应用

总结this,$router与this.$route的含义以及常见用法

 理解

this.$router:全局的路由对象,包含和很多属性和对象,任何页面都可以调用其方法。

this.$route:当前路由对象,是一个局部的路由对象,每一个路由都有一个route对象,可以使用其属性。

this.$router的方法

this.$router.push

通过修改url实现路由跳转,this.$router传递参数有两种方式

一、传递参数会拼接在路由后面,出现在地址栏

        传递参数:this.$router.push({path:‘路由’,query:{key:value}})

        参数取值:this.$route.query.key

二、传递参数不会拼接在路由后面,地址栏看不见参数

        传递参数:this.$router.push({name:'路由的name',params:{key:value}})

        参数取值:this.$route.params.key

注意:在this.$router.push中 path 也是传递params的。所以path与params 不能在一起使用或者提供首页地址

代码

// 字符串
this.$router.push('/index') 
// 对象
this.$router.push({path:'/index'})
// 带查询参数,变成/backend/order?selected=2/,query传参
this.$router.push({path:'/index', query:{name: '123'} })
// 命名的路由 params传参
this.$router.push({name:'index', params:{name: '123'} })

this.$router.replace

跳转到指定路由,替换history中最后一个记录,点击后退会返回至上一个页面(A->B->C被替换成A->C)

replace 属性默认为false,点击时不会留下history记录,push方法也可以传replace

// 声明式
<reouter-link :to="..." replace></router-link>
// 编程式:
router.replace(...)
// push方法也可以传replace
this.$router.push({path: '/homo', replace: true})

this.$router.go

在history中记录的前进或者后退val步

// 到下一页 前进一步
this.$router.go(1)

// 到上一页 后退一步
this.$router.go(-1)

this.$route

this.$route.query

获取this.$router.push中query的值,在URL中带参数

this.$route.params

获取this.$router.push中params的值,在URL中不带参数

this.$route.path

获取当前路由对象的路径

this.$route.name

获取当前路径名字

this.$route.matched

数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象

本文参考

https://blog.csdn.net/u014635374/article/details/116162950

$route 获取当前路径_$route.path_hhy980205的博客-CSDN博客

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值