vue3 router params传参数
时间: 2023-08-17 18:06:29 浏览: 52
在Vue 3中,你可以通过路由参数来传递参数。下面是一些示例代码来说明如何在Vue 3中使用路由参数传递参数:
1. 定义路由:
```javascript
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{
path: '/user/:id',
name: 'User',
component: UserComponent
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
```
2. 在组件中使用路由参数:
```javascript
<script>
export default {
mounted() {
const userId = this.$route.params.id;
// 使用userId进行一些操作
}
}
</script>
```
在上面的示例中,我们定义了一个带有路由参数的路由,参数名为`:id`。在`UserComponent`组件中,我们可以通过`this.$route.params.id`来获取传递的参数值。
你也可以在路由跳转时传递参数。例如:
```javascript
// 在某个方法中跳转并传递参数
this.$router.push({ name: 'User', params: { id: '123' } });
```
这将导航到名为`User`的路由,并将参数`id`设置为`123`。然后,在`UserComponent`组件中,你可以通过`this.$route.params.id`来获取传递的参数值。
希望这能帮到你!如果还有其他问题,请随时提问。