You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3项目动态路由修复:实现点击宠物卡片跳转对应id详情页

Vue3 动态路由跳转问题修复方案

1. 确认路由配置符合要求

你需要先检查router/index.js中的动态路由配置,确保动态参数名和后续传参的key一致,示例正确配置如下:

import { createRouter, createWebHistory } from 'vue-router'
import PetList from '@/components/PetList.vue'
import PetDetail from '@/components/PetDetail.vue'

const routes = [
  {
    path: '/',
    name: 'PetList',
    component: PetList
  },
  {
    // 这里动态参数必须是:id,和后续传参的key对应
    path: '/pet/:id',
    name: 'PetDetail',
    component: PetDetail
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

2. 修正PetList组件的router-link写法

最常见的错误是to属性没有加动态绑定标识:,或者参数名不匹配,两种正确写法如下:

字符串模板写法

<template>
  <div class="pet-list">
    <!-- 给每个宠物卡片套上router-link,必须加:绑定to的动态值 -->
    <router-link 
      v-for="pet in petList" 
      :key="pet.id"
      :to="`/pet/${pet.id}`"
    >
      <div class="pet-card">
        <!-- 卡片内容 -->
        <p>{{pet.name}}</p>
      </div>
    </router-link>
  </div>
</template>

对象传参写法(更推荐,路由路径修改后不用逐个改跳转逻辑)

<router-link 
  v-for="pet in petList" 
  :key="pet.id"
  :to="{ name: 'PetDetail', params: { id: pet.id } }"
>
  <div class="pet-card">
    <!-- 卡片内容 -->
  </div>
</router-link>

3. PetDetail组件正确获取参数匹配pet.json数据

路由params默认返回字符串类型,如果你的pet.json里id是数字类型,必须做类型转换,否则会匹配失败,组合式API示例如下:

<script setup>
import { ref, onMounted } from 'vue'
// 注意是useRoute不是useRouter,useRouter用来做编程式跳转,拿参数用useRoute
import { useRoute } from 'vue-router'
// 引入你的pet.json数据
import petList from '@/assets/pet.json'

const route = useRoute()
const currentPet = ref({})

onMounted(() => {
  // 把字符串类型的id转成数字,匹配json里的数字id
  const targetId = Number(route.params.id)
  currentPet.value = petList.find(item => item.id === targetId)
})
</script>

<template>
  <div class="pet-detail">
    <h2>{{currentPet.name}}</h2>
    <p>{{currentPet.desc}}</p>
    <!-- 其余详情内容 -->
  </div>
</template>

4. 排查其他异常点

  • 检查App.vue是否有<router-view />占位符,没有的话路由组件无法渲染
  • 检查pet.json的id字段是否存在重复、缺失的情况
  • 如果是编程式跳转(不用router-link),写法为router.push({ name: 'PetDetail', params: { id: xxx } })

内容的提问来源于stack exchange,提问作者Joan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:45:04