vue动态路由传参 this.$router和this.$route的区别
发布日期:2022-02-06 00:27:12 浏览次数:42 分类:技术文章

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

很多人对this. r o u t e r ∗ ∗ 和 ∗ ∗ t h i s . router** 和 **this. routerthis.route的区别不是很清楚

首先,我看来 this. r o u t e r 拿 到 的 是 n e w R o u t e r 并 且 在 每 个 创 建 出 来 的 组 件 中 都 会 被 赋 予 一 个 router拿到的是 new Router 并且在每个创建出来的组件中都会被赋予一个 routernewRouterrouter
然后,this. r o u t e 拿 到 的 是 r o u t e 路 由 规 则 中 被 激 活 的 当 前 组 件 ( 一 般 可 以 传 取 参 数 ) 因 此 , 组 件 接 受 传 过 来 的 值 一 般 都 是 t h i s . route拿到的是 route 路由规则中被激活的当前组件 (一般可以传取参数) 因此,组件接受传过来的值一般都是this. routeroute()this.route.params.id或
this.$route.query.id

进入正题:

**1.调用 r o u t e r . p u s h 实 现 携 带 参 数 的 跳 转 ∗ ∗ 方 法 内 使 用 : t h i s . router.push 实现携带参数的跳转** 方法内使用: this. router.push使this.router.push({ path: /about/${username} })

需要的路由配置如下:

{
path: ‘/home/:username’,
name: ‘home’,
component: Home,
}

另一个组件获取路由方式:

this.$route.params.username

2.query传递参数(命名路由传参)

注意:

1.命名路由传参 注意使用params不是queryquery会显示在地址栏中

方法内使用:

this.$router.push({ path: ‘/about’, query: { username: this.username } })

需要的路由配置如下:

{
path: ‘/home’,
name: ‘home’,
component: Home,
}

另一个组件获取路由方式:

this.$route.query.username

3.params传递参数(命名路由传参)

方法内使用:

this.$router.push({ name: ‘about’, params: { username: this.username } })

注:这里我发现个特别的 this.$router.push({ path: ‘/about’, params: { username: this.username } })当用params动态参数时用path来跳转是获取不到传递的参数值的,这个我也不是很清楚为什么不行。试了很多次。

需要的路由配置如下:

{
path: ‘/home’,
name: ‘home’,
component: Home,
}

另一个组件获取路由方式:

this.$route.params.username

转载地址:https://blog.csdn.net/weixin_46182770/article/details/120392260 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:These dependencies were not found:
下一篇:router.beforeEach 全局守卫 路由导航的用处及部分作用

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月01日 22时40分50秒