Router传参的几种方式
2022/7/26 6:52:55
本文主要是介绍Router传参的几种方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、普通不携带参数
- 父组件代码
<!-- app.vue --> <router-link to="/user">
- 路由配置
// router/index.js { path: '/user', name: 'User', component: User }
- 导航栏显示
http://localhost:8082/#/user
二、携带参数的几种方法
router-link
- 父组件代码
<!-- app.vue --> <router-link :to="`/user/${id}`"> <script> data() { return { id:123 } } </script>
- 路由配置
// router/index.js { path: '/user/:id', name: 'User', component: User }
- 导航栏显示
http://localhost:8082/#/user/123
- 子组件获取
// 通过 $route.params 获取所有传递的参数对象 this.$route.params // 通过指定key值获取准确的参数 this.$route.params.id
$router.push()
通过点击触发,直接跳转到指定页面
- 父组件代码
<!-- app.vue --> <button @click="goUser(456)">this.$router.push()-传参</button> <script> data() { methods: { goUser(id) { this.$router.push({ // 直接访问地址,类似第一种方式,只是一个是路由组件,一个是点击事件触发 path: `/user/${id}` }) } } } </script>
- 路由配置
// router/index.js { path: '/user/:id', name: 'User', component: User, }
- 导航栏显示
http://localhost:8082/#/user/456
- 子组件获取
// 通过 $route.params 获取所有传递的参数对象 this.$route.params // 通过指定key值获取准确的参数 this.$route.params.id
params
params 只能与 name 一起使用
跳转后不会将参数拼接到 url 上,刷新页面后参数会丢失
- 父组件代码
<!-- app.vue --> <button @click="goUser(789)">params-传参</button> <script> data() { methods: { goUser(id) { this.$router.push({ // name 必须与路由的 name 一致 name: 'User', params: { id } }) } } } </script>
- 路由配置
// router/index.js { path: '/user', name: 'User', component: User, }
- 导航栏显示
http://localhost:8082/#/user
- 子组件获取
// 通过 $route.params 获取所有传递的参数对象 this.$route.params // 通过指定key值获取准确的参数 this.$route.params.id
query
query 可以和 name 或者 path 一起搭配使用
跳转后在 url 后面拼接参数:?id=abc,非重要数据可以这样传,像密码之类使用 params
- 父组件代码
<!-- app.vue --> <button @click="goUser('abc')">query-传参</button> <script> data() { methods: { goUser(id) { this.$router.push({ // 直接填写 path ,或者使用 name // path: '/user', name: 'User' // 传参使用 query query: { id } }) } } } </script>
- 路由配置
// router/index.js { path: '/user', name: 'User', component: User, }
- 导航栏显示
http://localhost:8082/#/User?id=abc
- 子组件获取
// 通过 $route.query 获取所有传递的参数对象 this.$route.query // 通过指定key值获取准确的参数 this.$route.query.id
这篇关于Router传参的几种方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?