技术文摘
Vue3 中运用 Router 路由实现跳转传参的方法
Vue3 中运用 Router 路由实现跳转传参的方法
在 Vue3 开发中,使用 Router 路由实现页面跳转并传递参数是常见需求。合理运用路由传参能使页面间的数据交互更流畅,提升应用的用户体验。本文将详细介绍 Vue3 中运用 Router 路由实现跳转传参的方法。
1. 动态路由参数
动态路由参数是在路由路径中定义参数,通过这种方式可以将特定信息传递到目标页面。在 router/index.js 文件中定义路由时设置动态参数。例如:
const routes = [
{
path: '/user/:id',
name: 'User',
component: () => import('@/views/User.vue')
}
];
这里的 :id 就是动态参数。在跳转时,可以这样写:
<router - link :to="`/user/${userId}`">查看用户</router - link>
在目标组件 User.vue 中,可以通过 $route 对象获取参数:
export default {
setup() {
const route = useRoute();
const userId = route.params.id;
console.log(userId);
}
};
2. query 参数
query 参数以查询字符串的形式附加在 URL 后面。定义路由时无需特殊设置。在跳转时传递参数:
<router - link :to="{ path: '/home', query: { name: '张三', age: 25 } }">跳转到主页</router - link>
在目标组件中获取参数:
export default {
setup() {
const route = useRoute();
const name = route.query.name;
const age = route.query.age;
console.log(name, age);
}
};
query 参数的优点是传递的数据会显示在 URL 中,方便调试,但安全性相对较低,不适合传递敏感信息。
3. 路由守卫传参
路由守卫可以在路由切换前、切换后等阶段进行一些操作,也可以用来传参。例如,在 router/index.js 中使用 beforeEach 守卫:
router.beforeEach((to, from, next) => {
to.meta.userId = '123';
next();
});
在目标组件中获取参数:
export default {
setup() {
const route = useRoute();
const userId = route.meta.userId;
console.log(userId);
}
};
掌握 Vue3 中 Router 路由跳转传参的这些方法,能在开发中更高效地实现页面间的数据传递,满足各种业务需求,打造功能更强大、交互更流畅的应用程序。
TAGS: Vue3 Router路由 跳转传参 Vue3路由跳转传参
- GO 语言导入自身编写的包(同级与不同级目录)
- Linux 中 pidstat 命令监控进程性能的操作指南
- Python 项目打包为 apk 及其他端应用程序
- Windows 软件授权管理工具 slmgr 命令使用教程
- Python docx 段落对齐的实现方法
- pandas 表连接的实际实现方式
- Python 本地.whl 文件的安装流程与注意要点
- Python 为现有 DataFrame 添加新列的示例代码
- Python 借助 WebSocket 与 SSE 实现 HTTP 服务器消息推送
- Python 中 Google Authenticator 认证流程
- Python 借助 Transformers 达成机器翻译功能
- Python 中 http.server 库的详细用法介绍
- Python 中 requests 代理服务器的设置
- Python 中求最小公倍数与最大公约数的代码实例及解题思路
- Python 实现最小公倍数的方法示例