在 Vue 3 里,你可以借助 $router.push
方法进行路由跳转,同时传递多个路径参数。下面为你详细介绍具体实现方式:
1. 路由配置
首先,要在路由配置中定义好需要的路径参数。示例如下:
import { createRouter, createWebHistory } from 'vue-router';
import UserProfile from './views/UserProfile.vue';const routes = [{path: '/user/:id/:name',name: 'UserProfile',component: UserProfile}
];const router = createRouter({history: createWebHistory(),routes
});export default router;
在这个路由配置里,/user/:id/:name
定义了两个路径参数:id
和 name
。
2. 使用 $router.push
传递多个路径参数
在组件中,你可以使用 useRouter
来获取路由实例,然后使用 push
方法传递多个路径参数
<template><div><button @click="goToUserProfile">跳转到用户资料页</button></div>
</template><script setup>
import { useRouter } from 'vue-router';const router = useRouter();const goToUserProfile = () => {router.push({name: 'UserProfile',params: {id: 123,name: 'JohnDoe'}});
};
</script>
3. 在目标组件中接收参数
在目标组件 UserProfile.vue
里,你可以使用 useRoute
来获取路由信息,进而获取传递的路径参数。
<template><div><h1>用户资料页</h1><p>用户 ID: {{ route.params.id }}</p><p>用户姓名: {{ route.params.name }}</p></div>
</template><script setup>
import { useRoute } from 'vue-router';const route = useRoute();
</script>
注意事项
- 参数顺序:在路由配置里,路径参数的顺序是固定的。例如
/user/:id/:name
,传递参数时要保证顺序一致。 - 参数类型:路径参数在 URL 中以字符串形式存在,即便传递的是数字,接收时也会是字符串类型。若需要使用其他类型,要进行相应的类型转换。