VueJS页面重载后方法不执行,仅VS Code保存后执行求助
问题描述
页面重载后,pushButtonIds方法里的console.log完全没输出,说明这方法根本没执行;但在VS Code里改完代码保存触发热更新后,这方法又能正常跑起来。把表单所在弹窗的显示/隐藏逻辑删掉,问题还是存在。试过在beforeCreated钩子调用它,同样没用。
相关代码:
created() { this.loadStationList(); this.loadStationGroups(); this.loadAllButtons(); this.loadAllQuidos(); this.pushButtonIds(); // 想在created里执行,但只有VS Code改存后才生效 },
pushButtonIds() { for (const buttonId in this.filteredButtonList) { this.stationButtons.push({ buttonId: this.filteredButtonList[buttonId].buttonListId, quidoId: null, input: null, }); console.log(this.stationButtons); console.log("Hello from component after saving change in VSC"); } },
问题根源
pushButtonIds完全依赖this.filteredButtonList的数据,但loadAllButtons这类加载方法大概率是异步操作(比如调用后端接口),在created里同步调用pushButtonIds的时候,filteredButtonList还没拿到数据,循环根本跑不起来,自然看不到日志输出。
而VS Code改存后触发热更新,此时组件重新渲染时filteredButtonList已经有缓存的数据了,所以方法能正常执行。
解决办法
- 等异步加载完再调用方法
如果loadAllButtons这些方法返回Promise(比如用axios请求的话本身就支持),直接用async/await顺序执行:
async created() { await this.loadStationList(); await this.loadStationGroups(); await this.loadAllButtons(); await this.loadAllQuidos(); this.pushButtonIds(); },
- 监听数据变化自动触发方法
给filteredButtonList加个监听器,数据更新就调用方法:
watch: { filteredButtonList: { immediate: true, // 组件初始化时直接执行一次 handler() { this.pushButtonIds(); } } },
不管是首次加载还是后续数据更新,只要filteredButtonList有变化,都会触发pushButtonIds。
- 给方法加个空数据判断
避免因为数据为空导致循环不执行,加个判断逻辑:
pushButtonIds() { if (!this.filteredButtonList || Object.keys(this.filteredButtonList).length === 0) { console.log("filteredButtonList 还没数据"); return; } // 原有循环逻辑 for (const buttonId in this.filteredButtonList) { this.stationButtons.push({ buttonId: this.filteredButtonList[buttonId].buttonListId, quidoId: null, input: null, }); console.log(this.stationButtons); console.log("Hello from component after saving change in VSC"); } },
内容的提问来源于stack exchange,提问作者martin-den
相关产品推荐
相关产品推荐

