Vue.js数据状态无法更新:天气应用异步方法修改后取值异常
问题原因
你遇到的问题核心是异步操作的执行顺序:
getGeolocationInformation是异步方法,里面的fetch请求需要时间返回结果,修改data字段的逻辑要等请求完成后才会执行。- 在
created钩子中,你调用getGeolocationInformation后,JS不会等待这个异步方法执行完毕,立刻就去执行getCoordinatesCityByName——这时候异步请求还没返回,lon还是初始的0值,自然拿不到更新后的数据。
解决方案
给你两种简单的修复方式:
方式一:让created等待异步方法执行完成
把created改成异步函数,用await等待getGeolocationInformation执行完再调用后续方法:
async created () { await this.getGeolocationInformation() this.getCoordinatesCityByName() }
方式二:在异步方法内完成后调用目标方法
直接在getGeolocationInformation的最后,等数据修改完成后调用getCoordinatesCityByName:
async getGeolocationInformation () { const API_KEY = 'REPLACE_WITH_VALID_API_KEY' const API_URL = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + API_KEY const apiResponse = await fetch(API_URL) const data = await apiResponse.json() const { city, country, region } = data this.city = city // 这里没必要用this.$data,直接this.city更规范 this.region = region this.country = country this.lon = 100 // 请求完成、数据更新后再调用 this.getCoordinatesCityByName() }
然后把created里的getCoordinatesCityByName()删掉即可。
额外提示
代码里的this.$data.city = city可以直接写成this.city = city,Vue已经做好了响应式绑定,直接通过this.属性名修改就足够,不需要直接操作$data对象。
内容的提问来源于stack exchange,提问作者Владислав
相关产品推荐
相关产品推荐

