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

Vue3宝可梦CRUD应用二次点击进化按钮报TypeError错误求助

Vue3宝可梦应用进化按钮二次点击报错问题解决

问题描述

开发基于Vue3的全世代宝可梦初始精灵CRUD应用,点击宝可梦卡片可打开模态框查看详情,模态框内的进化按钮首次点击正常,但二次点击时出现错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'length')

错误原因

第一次点击进化按钮时,currpkmn是从卡片传入的根宝可梦对象(包含evolutionline完整进化链数组),点击后通过$emit将currpkmn更新为evolutionline中的子对象,但这些子对象没有evolutionline属性(查看JSON样本可知,仅根对象包含完整进化链)。二次点击时,this.currpkmn.evolutionline为undefined,读取length就会触发报错。

解决方案

在模态框组件内部保存初始的完整进化链数组,而非每次从当前currpkmn中读取,同时监听currpkmn变化重置当前进化索引:

修改ModalComponent.vue代码

  1. 在data中新增变量保存完整进化链:
data() {
  return {
    currIndex: 0,
    evolutionLine: [] // 新增:存储当前宝可梦的完整进化链
  };
}
  1. 添加watch监听currpkmn变化,初始化进化链和对应索引:
watch: {
  currpkmn(newVal) {
    if (newVal?.evolutionline) {
      this.evolutionLine = newVal.evolutionline;
      // 定位当前宝可梦在进化链中的位置,确保索引准确
      this.currIndex = this.evolutionLine.findIndex(p => p.num === newVal.num);
    }
  }
}
  1. 重写evolve方法,基于保存的进化链执行切换逻辑:
methods: {
  evolve() {
    // 防御判断:进化链为空则终止执行
    if (!this.evolutionLine.length) return;
    
    // 循环切换索引:到达进化链末尾后自动回到开头
    this.currIndex = (this.currIndex + 1) % this.evolutionLine.length;
    this.$emit("update:currpkmn", this.evolutionLine[this.currIndex]);
  }
}
  1. 优化gradient计算属性,避免空值访问报错:
computed: {
  gradient() {
    if (!this.currpkmn?.types) return "white";
    
    const primaryType = this.currpkmn.types[0];
    if (primaryType === "Water") {
      return `radial-gradient(circle at center, #acddfe, #2ea1fe)`;
    }
    if (primaryType === "Fire") {
      return `radial-gradient(circle at center, #fec3ac, #fe4d2e)`;
    }
    if (primaryType === "Grass") {
      return `radial-gradient(circle at center, #d1feac, #2efe5b)`;
    }
    return "white";
  }
}

补充说明

该方案无需修改原始JSON数据结构,通过组件内部缓存完整进化链解决问题;新增的防御判断和索引重置逻辑,确保切换不同宝可梦时进化功能仍能正常工作。

内容的提问来源于stack exchange,提问作者Pascal R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:11:48