You need to enable JavaScript to run this app. Vue3使用vue-router命名路由跳转报错Cannot read property 'name' of undefined
优惠活动
大模型
产品
解决方案
定价
更多

Vue3使用vue-router命名路由跳转报错Cannot read property 'name' of undefined

问题根因

你遇到的报错核心是destination计算属性返回了undefined,所以访问destination.name失败,两个直接原因:

  • 路由未声明接收id参数,导致传参无效/参数丢失
  • 参数类型不匹配,查找逻辑无法命中store中的数据

修复步骤

步骤1:修改路由配置,声明参数

修改src/router/index.js中DestinationDetails对应的路由项,给path增加id参数占位:

{
  path: "/details/:id", // 增加:id占位,声明接收id参数
  name: "DestinationDetails",
  component: () => import(/* webpackChunkName: "DestinationDetails" */ '@/views/DestinationDetails')
}

步骤2:修正参数类型匹配逻辑

路由默认传递的params.id是字符串类型,而你store中存储的id是数字类型,===严格相等判断会匹配失败,把DestinationDetails中destinationId的赋值改为转数字即可:

data() {
  return {
    destinationId: Number(this.$route.params.id) // 转为数字类型,匹配store中的id格式
  }
}

可选优化:增加兜底逻辑避免报错

可以在模板中使用可选链,或者加条件渲染,防止极端情况(比如id不存在)下页面空白:

<!-- 写法1:可选链 -->
<h1>{{ destination?.name }}</h1>
<img :src="require(`@/assets/${destination?.image}`)" :alt="destination?.name">

<!-- 写法2:条件渲染 -->
<section class="destination" v-if="destination">
  <h1>{{ destination.name }}</h1>
  <div class="destination-details">
    <img :src="require(`@/assets/${destination.image}`)" :alt="destination.name">
  </div>
</section>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 17:36:11