Vue中如何在@click事件中向路由传递索引参数?
最优实现方案
1. 完善循环逻辑并传递索引到路由
先修改v-for循环,添加索引变量(同时绑定:key保证Vue渲染性能),跳转时把索引作为参数传入路由:
<div class="md:grid-cols-2 lg:grid-cols-1 col-gap-2 md:col-gap-8 md:row-gap-10" v-for="(c, index) in 4" :key="index"> <Course @click="$router.push(`/detail/${index + 1}`)" <!-- 索引从1开始更贴合业务ID习惯,也可直接用index --> title="The Course" description="A Course" lessons="1" length="1 hr" /> </div>
注:后续遍历对象列表时,直接把
index换成course.id(假设对象带id字段)即可,扩展性更强。
2. 路由配置与参数接收(推荐路径参数方式)
这种方式让URL更语义化(比如/detail/1),是详情页场景的最优选择:
步骤1:配置路由规则
在路由配置文件中,将/detail改成带路径参数的形式:
// router/index.ts import { createRouter, createWebHistory } from 'vue-router' import Detail from '@/views/Detail.vue' const routes = [ // ...其他路由 { path: '/detail/:id', // :id 为路径参数 name: 'Detail', component: Detail, props: true // 开启后,路径参数会自动作为props传入组件 } ] const router = createRouter({ history: createWebHistory(), routes }) export default router
步骤2:详情页接收参数
因为开启了props: true,你原有的组件代码无需改动,直接用props.id就能拿到值:
<template> Course Details {{ props.id }} </template> <script setup lang="ts"> const props = defineProps(['id']) </script>
如果不想用props,也可以通过useRoute直接获取参数:
<script setup lang="ts"> import { useRoute } from 'vue-router' const route = useRoute() // 路径参数存于route.params中 const courseId = route.params.id </script>
3. 备选:查询参数方式(适合非核心参数场景)
如果不想修改路由路径,也可以用查询参数(URL形如/detail?id=1):
- 跳转代码修改为:
<Course @click="$router.push({ path: '/detail', query: { id: index + 1 } })" <!-- ...其他属性 --> />
- 详情页接收参数:
<script setup lang="ts"> import { useRoute } from 'vue-router' const route = useRoute() const courseId = route.query.id </script>
额外优化:让Course组件更内聚
如果后续每个Course都需要跳转,建议把跳转逻辑封装到Course组件内部,父组件只传courseId即可:
<!-- Course.vue --> <template> <div @click="handleJump" class="course-card"> <h3>{{ title }}</h3> <!-- ...组件其他内容 --> </div> </template> <script setup lang="ts"> import { useRouter } from 'vue-router' const router = useRouter() const props = defineProps({ title: String, description: String, lessons: String, length: String, courseId: Number // 接收父组件传递的ID }) const handleJump = () => { router.push(`/detail/${props.courseId}`) } </script>
父组件调用时:
<div v-for="(c, index) in 4" :key="index"> <Course :course-id="index + 1" title="The Course" description="A Course" lessons="1" length="1 hr" /> </div>
这种方式让组件职责更清晰,避免父组件重复编写跳转逻辑。
内容的提问来源于stack exchange,提问作者Mike3355
相关产品推荐
相关产品推荐

