有两种方法在 Vue.js 中传递路由参数:编程式导航:使用 $router.push() 或 $router.replace(),并通过 to 选项传递参数。具名路由:在路由配置中定义具名路由,并使用冒号语法 (:param) 指定参数,然后在导航中使用路由名称并通过 params` 选项传递参数。
如何使用 Vue.js 传递路由参数
在 Vue.js 中,有两种主要方法可以传递路由参数:
1. 使用编程式导航
你可以使用 $router.push() 或 $router.replace() 方法编程式地导航到一个新的路由,并通过 to 选项传递参数:
立即学习“前端免费学习笔记(深入)”;
this.$router.push({ path: '/user/:id', params: { id: 123 } });
2. 使用具名路由
你可以在路由配置对象中定义具名路由,并通过 :param 语法在路由路径中指定参数:
const routes = [ { path: '/user/:id', name: 'User' } ];
然后,你可以在导航时使用路由的名称,并通过 params 选项传递参数:
this.$router.push({ name: 'User', params: { id: 123 } });
在组件中访问路由参数
在目标组件中,你可以通过 $route.params 访问路由参数:
export default { computed: { userId() { return this.$route.params.id; } } };
以上就是vue路由怎么传递的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号