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

Vue3开发扫雷时计算属性cellsLeft出现NaN的问题排查

问题解决:计算属性cellsLeft返回NaN的原因及修复

你的cellsLeft计算属性返回NaN的核心原因是引用了未定义的变量:在计算逻辑里你写了this.Bombs,但组件props中定义的地雷数量属性是numBombs,所以this.Bombs的值为undefined。当数字与undefined进行减法运算时,结果就会变成NaN。

修复步骤

1. 修正计算属性的变量名

将computed中的this.Bombs改为this.numBombs:

computed: {
  cellsLeft() {
    return this.numCells - this.numBombs - this.numRevealed
  }
}

2. 可选优化:将numCells改为计算属性

目前你把numCells放在data中,只会在组件初始化时计算一次。如果后续需要动态修改width或height,numCells不会自动更新。建议把它也改成计算属性:

data() {
  return {
    numRevealed: 0,
    field: this.createField(),
  };
},
computed: {
  numCells() {
    return this.height * this.width
  },
  cellsLeft() {
    return this.numCells - this.numBombs - this.numRevealed
  }
}

验证效果

修复后,当numRevealed增加时,cellsLeft会正确计算剩余非地雷单元格数量。当cellsLeft变为0时,watch监听器会触发获胜提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:21:31