Vue 中让方法同步执行
有很多小伙伴在使用Vue的时候都会遇到一种情况,form表单修改回显时,某个下拉框里的内容回显乱码,如下图所示:
这是因为Vue是的请求方法是异步请求:简单来说,form表单内容先获取了出来,而项目阶段的下拉框随后才获取出来。
// 表单
<el-col :span="12">
<el-form-item :label="$t('项目阶段')" prop="dealStage">
<el-select v-model="form.dealStage" :placeholder="$t('自动回显')" filterable>
<el-option
v-for="item in dealStageOptions"
:key="item.id"
:label="item.nodeName"
:value="item.id" />
</el-select>
</el-form-item>
</el-col>
// data 数据
data () {
return {
// 项目阶段下拉数据
dealStageOptions: [],
// 表单数据
form: {}
}
},
// 初始化方法
init(id) {
// 获取项目阶段下拉数据(dealStageOptions),
// getDealStageListInfo方法的请求时间可能比获取表单基本信息的请求时间长,不能在表单数据获取之前获取出来。(getDealStageListInfo方法的响应时间比getFormInfo方法的响应时间久)
this.getDealStageListInfo()
this.getFormInfo(id) // 获取表单基本信息数据(form)
},
// 获取节点下拉数据方法
getDealStageListInfo () {
getNodeListByDealType().then(res => {
if (res.code === 200) {
this.dealStageOptions = res.rows
}
})
},
// 获取表单数据方法
getFormInfo(id) {
getDealBase(id).then( response => {
if(response.code === 200) {
this.form = response.data
}
})
},
因此解决该问题的出现有几种方法。
第一种(不推荐),当项目阶段的下拉框数据请求完成后再请求form表单数据(也就是吧form表单的请求嵌套到下拉框请求结果后请求)如下:
init(id) {
getDealStageListInfo (id) {
getNodeListByDealType().then(res => {
if (res.code === 200) {
this.dealStageOptions = res.rows
getDealBase(id).then( response => {
this.form = response.data
})
}
})
}
},
这种方式并不是最好的方式,因为当返回参数 res.code 不等于200时,会导致form表单获取不到数据。
第二种:使用async和await关键字
async 和 await 关键字是ES6语法提供的,用于同步调用
// 初始化表单数据方法
// 使用async 和 await 关键字保证该方法体内容能按顺序执行
async init(id) {
await this.getDealStageListInfo()
await this.getFormInfo(id)
},
// 获取节点下拉数据方法
getDealStageListInfo () {
getNodeListByDealType().then(res => {
if (res.code === 200) {
this.dealStageOptions = res.rows
}
})
},
// 获取表单数据方法
getFormInfo(id) {
getDealBase(id).then( response => {
if(response.code === 200) {
this.form = response.data
}
})
},
使用同步调用后就不再出现表单回显乱码的问题!
结语:
当然,保持方法同步调用的方式有很多,各位小伙伴们有什么更好的方案可以关注并评论讨论!
感谢各位“码友”的支持!