// Vue 3 Router 传参示例
// 1. 定义路由
const routes = [
{
path: '/user/:id', // 动态路径参数
name: 'User',
component: UserComponent,
},
{
path: '/product',
name: 'Product',
component: ProductComponent,
props: true, // 启用 props 传参
},
];
// 2. 创建路由实例
const router = createRouter({
history: createWebHistory(),
routes,
});
// 3. 在组件中接收参数
// 方式一:使用 $route.params 获取动态路径参数
export default {
name: 'UserComponent',
mounted() {
console.log(this.$route.params.id); // 获取路径中的 id 参数
},
};
// 方式二:通过 props 接收参数(适用于在定义路由时启用了 props: true)
export default {
name: 'ProductComponent',
props: ['id'], // 在路由配置中启用 props 后,可以直接通过 props 接收参数
mounted() {
console.log(this.id); // 直接使用 this.id 获取参数
},
};
// 4. 路由跳转并传参
this.$router.push({ name: 'User', params: { id: 123 } }); // 动态路径参数传参
this.$router.push({ name: 'Product', params: { id: 456 } }); // 通过 props 传参
:id 这样的占位符定义动态路径参数,在目标组件中可以通过 this.$route.params 获取。props: true,可以让组件直接通过 props 接收参数,这种方式更简洁。this.$router.push() 方法进行页面跳转时,可以通过 params 或 query 方式传递参数。上一篇:vue 图表组件
下一篇:vue3 子路由
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站