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-0601-电商商品中心解密:仅凭SKU真的足够吗?
- 2024-05-01为什么公共事业机构会偏爱 TiDB :TiDB 数据库在某省妇幼健康管理系统的应用
- 2024-04-26敏捷开发:想要快速交付就必须舍弃产品质量?
- 2024-04-26静态代码分析的这些好处,我竟然都不知道?
- 2024-04-26你在测试金字塔的哪一层?(下)
- 2024-04-26快刀斩乱麻,DevOps让代码评审也自动起来
- 2024-04-262024年最好用的10款ER图神器!
- 2024-04-2203-为啥大模型LLM还没能完全替代你?
- 2024-04-2101-大语言模型发展
- 2024-04-17基于SpringWeb MultipartFile文件上传、下载功能