随笔 - 19  文章 - 0  评论 - 1  阅读 - 8753

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

 

解决该问题的出现有几种方法:

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

 

2. 当项目阶段的下拉框数据请求完成后再请求form表单数据(也就是吧form表单的请求嵌套到下拉框请求结果后请求) (不推荐)

这种方式并不是最好的方式,因为当返回参数 res.code 不等于200时,会导致form表单获取不到数据。

init(id) {
  getDealStageListInfo (id) {
    getNodeListByDealType().then(res => {
      if (res.code === 200) {
        this.dealStageOptions = res.rows
        getDealBase(id).then( response => {
          this.form = response.data
        })
      }
    })
  }
},

posted on   阿宇爱吃鱼  阅读(340)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示