Vue.js选择城市触发getState API首次调用数据滞后问题求助
问题根因
- 方法定义位置错误:
getCity、getStates方法没有声明在methods配置项内,Vue实例无法正确识别调用。 - 选中值获取时机错误:Vue Multiselect的
@select事件触发时机早于v-model的更新时机,你直接在getStates中读取this.selectedCity拿到的是上一次的选中值,导致每次请求携带的都是旧的cityId,返回结果自然慢一拍。 - 生命周期执行顺序错误:
beforeMount中先调用getCity再赋值token,导致第一次拉取城市列表的请求头里Authorization为undefined,可能请求失败。 - 加载状态赋值位置错误:
apiLoaded直接写在异步请求外部,会在请求还没返回时就提前标记为加载完成。
修复方案
1. 修正JS代码结构
<script> import VueMultiselect from "vue-multiselect"; export default { data: function() { return { cityId: "", selectedCity: "", cities: [], option: [], option1: [], selectedState: "", selectedCountry: "", apiLoaded: false // 补充声明data中遗漏的apiLoaded变量 }; }, // 所有业务方法统一放到methods配置项中 methods: { getCity() { this.axios .get(this.baseURL + "cities", { headers: { Authorization: "Bearer " + this.token, }, }) .then((response) => { this.cities = response.data.data; console.warn(response.data.data); }) .catch((err) => { console.log(err) }) .finally(() => { this.apiLoaded = true; // 请求结束后再更新加载状态 }) }, // 直接接收@select事件返回的当前选中城市作为参数,避免读取旧的v-model值 getStates(selectedCity) { this.cityId = selectedCity.id; this.axios .get(this.baseURL + "states", { params: { id: this.cityId, }, headers: { Authorization: "Bearer " + this.token, }, }) .then((response) => { this.option = response.data.data.option; this.option1 = response.data.data.option1; // 切换城市后清空之前选中的省和国家 this.selectedState = "" this.selectedCountry = "" console.warn(response.data.data.option); console.warn(response.data.data.option1); }) .catch((err) => { console.log(err); }) .finally(() => { this.apiLoaded = true; }) }, // 剩余用到的addCity、addState、addCountry方法也统一放到此处 }, components: { VueMultiselect, }, beforeMount() { // 先赋值token再调用接口,避免请求头权限缺失 this.token = "token updated"; console.warn(this.token); this.getCity(); }, }; </script> <style src = "vue-multiselect/dist/vue-multiselect.css" > </style>
2. 修正模板中@select事件绑定
<VueMultiselect class=" mt-1.5 w-72 shadow-smNew rounded-xl py-4 pl-4 text-lg " v-model="selectedCity" tag-placeholder="Add this as new city" placeholder="Search or add a city" label="city_name" track-by="id" :options="cities" :multiple="false" :taggable="true" @tag="addCity" @select="getStates" <!-- 去掉括号直接传方法名,自动将选中值作为参数传入 --> ></VueMultiselect>
修改完成后即可保证每次选择城市都会携带当前选中的cityId发起请求,返回的最新数据会实时同步到省、国家下拉选项中。
内容的提问来源于stack exchange,提问作者Geeta Ninawe
相关产品推荐
相关产品推荐

