生成一个vue3的动态路由代码
时间: 2023-11-06 18:01:25 浏览: 45
好的,以下是一个简单的动态路由的 Vue 3 代码示例:
```javascript
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/about/:id',
name: 'About',
component: () => import('@/views/About.vue'),
props: (route) => ({ id: route.params.id })
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
在上面的代码中,我们定义了两个路由:一个是根路由,另一个是带有动态参数的路由。动态参数 `:id` 被定义在路由的路径中,然后通过 `props` 将其传递给组件。在组件中,我们可以通过 `props` 中的 `id` 属性获取该参数的值。
这里使用了 `createWebHistory` 创建路由的历史记录,你也可以使用 `createMemoryHistory` 或 `createWebHashHistory` 来创建不同类型的路由。最后,将路由对象导出,以供应用程序使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)