Vue 中请求同步执行解决方案

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
		}
	})
},

同步调用后正常显示
使用同步调用后就不再出现表单回显乱码的问题!

结语:

当然,保持方法同步调用的方式有很多,各位小伙伴们有什么更好的方案可以关注并评论讨论!
感谢各位“码友”的支持!

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醒省行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值