在 Vue 3 中,实现动态路由可以按照以下详细步骤进行操作:
-
在 Vue 路由配置文件中,使用占位符定义动态路由的路径:
javascriptCopy Code
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import MyComponent from '@/components/MyComponent.vue'
const routes = [
{
path: '/my-route/:id',
name: 'MyComponent',
component: MyComponent
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
在这个例子中,我们定义了一个动态路由 /my-route/:id
,其中 :id
是一个占位符,表示一个动态的参数。这样,无论是 /my-route/123
还是 /my-route/456
都会匹配到同一个组件。
-
在要接收动态参数的组件中,可以通过
this.$route.params
来访问动态路由中的参数:
htmlCopy Code
<!-- MyComponent.vue -->
<template>
<div>
<p>当前的动态参数为:{{ $route.params.id }}</p>
</div>
</template>
<script>
export default {
// ...
}
</script>
在这个例子中,我们使用了 this.$route.params.id
来获取动态路由中传递的参数,并在组件中进行展示。
-
若要生成带有动态参数的链接并进行页面跳转,可以使用
<router-link>
或者编程式导航(通过this.$router.push
)的方式:
htmlCopy Code
<!-- 在其他组件中 -->
<router-link :to="'/my-route/' + dynamicId">跳转到动态路由</router-link>
javascriptCopy Code
// 在其他代码中
this.$router.push('/my-route/' + dynamicId);
在这个例子中,我们使用字符串拼接的方式来生成带有动态参数的链接,并通过 <router-link>
或者编程式导航进行页面跳转。
这样,您就可以在 Vue 3 中实现动态路由。当访问 /my-route/123
或者 /my-route/456
时,都会渲染 MyComponent
组件,并且您可以通过 this.$route.params.id
获取到动态传递的参数值。