Vue3 路由声明中如何声明带参的路由
时间: 2024-05-12 12:13:35 浏览: 14
在 Vue3 中声明带参的路由需要使用动态路由参数。具体步骤如下:
1. 在 `router.js` 文件中定义路由。例如:
```javascript
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import Detail from './views/Detail.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/detail/:id',
name: 'Detail',
component: Detail
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
2. 在路由声明中指定动态参数。例如,上面的路由中,`Detail` 路由的 `path` 中包含了一个动态参数 `:id`,表示这个路由可以接受一个名为 `id` 的参数。
3. 在组件中使用 `$route.params` 获取路由参数。例如,在 `Detail` 组件中,可以通过 `$route.params.id` 获取传递的 `id` 值。
```vue
<template>
<div>
Detail Page, id: {{ $route.params.id }}
</div>
</template>
```
注意:在 Vue3 中,使用 `$route` 访问路由对象会报警告,建议使用 `useRoute()` Hook 获取路由对象。例如:
```vue
<template>
<div>
Detail Page, id: {{ route.params.id }}
</div>
</template>
<script>
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
return {
route
}
}
}
</script>
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)