博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Vue 中 this.$router 与 this.$route 的区别 以及 push() 方法
阅读量:3986 次
发布时间:2019-05-24

本文共 1775 字,大约阅读时间需要 5 分钟。

官房文档里是这样说明的:

通过注入路由器,我们可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前路由

可以理解为:

this.$router 相当于一个全局的路由器对象,包含了很多属性和对象(比如 history 对象),任何页面都可以调用其 push(), replace(), go() 等方法。

this.$route 表示当前路由对象,每一个路由都会有一个 route 对象,是一个局部的对象,可以获取对应的 name, path, params, query 等属性。

关于 push() 方法:

想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

当你点击 <router-link> 时,这个方法会在内部调用,所以说,点击 <router-link :to="..."> 等同于调用 router.push(…)。

push() 方法的调用:

//字符串this.$router.push('home')//对象this.$router.push({
path:'home'})//命名的路由this.$router.push({
name:'user', params:{
userId: '123'}})//带查询参数,变成 /register?plan=privatethis.$router.push({
path:'register', query:{
plan:private}})

注意:如果提供了 path,params 会被忽略,上述例子中的 query 并不属于这种情况。取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path:

const userId = '123';this.$router.push({
path:`/user/${
userId}`}); //->/user/123this.$router.push({
name:'user', params:{
userId}}); //->/user/123//这里的 params 不生效this.$router.push({
path:'/user', params:{
userId}}); //->/user

同样的规则也适用于 router-link 组件的 to 属性。

总结:

params 传参,push 里面只能是 name:‘xxx’,不能是 path:’/xxx’,因为 params 只能用 name 来引入路由,如果这里写成了 path ,接收参数页面会是 undefined。

路由传参的方式:

1、手写完整的 path:     this.$router.push({
path: `/user/${
userId}`}); 获取参数:this.$route.params.userId 2、用 params 传递: this.$router.push({
name:'user', params:{
userId: '123'}}); 获取参数:this.$route.params.userId url 形式:url 不带参数,http:localhost:8080/#/user 3、用 query 传递: this.$router.push({
path:'/user', query:{
userId: '123'}}); 获取参数:this.$route.query.userId url 形式:url 带参数,http:localhost:8080/#/user?userId=123

直白的说,query 相当于 get 请求,页面跳转的时候可以在地址栏看到请求参数,params 相当于 post 请求,参数不在地址栏中显示。

要注意,以 / 开头的嵌套路径会被当作根路径。 这让你充分的使用嵌套组件而无须设置嵌套的路径。

转载地址:http://sjaui.baihongyu.com/

你可能感兴趣的文章
头条搜索部门后台开发实习生面经
查看>>
java 线程池
查看>>
设计模式之单例模式
查看>>
自己写的String类能够被加载吗?
查看>>
java让主线程等待所有子线程执行完应该怎么做
查看>>
如此调用
查看>>
计算机的发展史
查看>>
二叉树两个节点最近公共祖先的解法
查看>>
三个线程轮流打印0到10
查看>>
RocketMQ 编译 不再支持源选项6
查看>>
Cpu、核、Java Runtime.getRuntime().availableProcessors()
查看>>
阶乘的对某个质因子P的分解
查看>>
字符串匹配问题,返回第一个匹配的下标 ,运用了KMP算法
查看>>
逆序单链表 时间复杂度O(n)
查看>>
创建二叉树、递归/非递归 先序/中序/后序遍历二叉树算法
查看>>
未排序数组中累加为给定值的最长子数组问题。
查看>>
软件工程
查看>>
归并排序
查看>>
快速排序
查看>>
堆排序
查看>>