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
相关产品推荐
相关产品推荐

