Vue3+Phaser+Spine.js报错:Cannot read properties of undefined (reading 'data')
解决Phaser Vue3项目中Spine插件调用
this.add.spine报Cannot read properties of undefined (reading 'data')错误 修复步骤
1. 修正场景注册笔误
你的main.js配置里scene数组写的是[game],但实际要加载的场景是Lootbox,这会导致场景和插件绑定失败:
// main.js 修正后 const config = { // ...其他配置项 scene: [Lootbox] // 替换原有的[game] };
2. 优化Spine插件注册
确保插件配置正确,添加start: true强制插件随场景启动初始化:
plugins: { scene: [ { key: 'SpinePlugin', plugin: SpinePlugin, mapping: 'spine', start: true } ] },
3. 确保资源与插件都准备就绪后再创建Spine实例
在Vue异步环境下,即使preload执行完毕,插件可能还未完成初始化,通过加载完成回调确保时机正确:
create() { const initSpine = () => { const manAnimation = this.add.spine(333, 333, 'man-data', "idle", true); manAnimation.animationState.setAnimation(0, "in", true); }; if (this.load.isComplete()) { initSpine(); } else { this.load.once('complete', initSpine); } }
4. 统一Spine资源加载方式
改用this.load.spine方法自动适配资源格式,避免格式不匹配问题:
preload() { // 合并加载骨骼和图集 this.load.spine('man', 'assets/man.skel', 'assets/man.atlas', true); } // create中调用时使用统一的key 'man' const manAnimation = this.add.spine(333, 333, 'man', "idle", true);
5. 确保Vue DOM挂载完成后启动游戏
在Vue组件的onMounted钩子中启动Phaser,避免DOM容器未就绪导致的初始化异常:
<script setup> import StartGame from './main.js'; import { onMounted } from 'vue'; onMounted(() => { StartGame('game-container'); }); </script>
问题根源
原生JS项目正常但Vue3项目报错,核心原因是:
- Vue的异步DOM挂载机制导致Phaser启动时机过早,插件未完成初始化
- 配置中的场景注册错误,使插件无法绑定到目标场景
- Vue环境下资源加载与插件初始化的顺序需要更严格的控制
内容的提问来源于stack exchange,提问作者liviu vasilescu
相关产品推荐
相关产品推荐

