循环数组调接口,按顺序返回对应数据

1. async+await

    <div v-for="(item, index) in list" :key="index">
      <span> {
   
   { item }} </span>
    </div>
//数据依次增加,页面依次渲染
    async aaa () {
    
    
      this.arr1=[]
      for (let index = 0; index < this.list.length; index++) {
    
    
        await getXX(this.list[index].id).then(res => {
    
    
          this.arr1.push(res.data.name)
        })
      }
    },
 //数据一步到位,页面渲染一次
    async aaa () {
    
    
      let arr=[]
      for (let index = 0; index < this.list.length; index++) {
    
    
        await getXX(this.list[index].id).then(res => {
    
    
          this.arr1.push(res.data.name)
        })
      }
       this.arr1=arr
    },

2. promise

    <div v-for="(item, index) in list" :key="index">
      <span> {
   
   { item }} </span>
    </div>
	fun1(id){
    
    
      return new Promise((resolve, reject) => {
    
    
        getXX(id).then(res => {
    
    
          let name= res.data.name
          resolve(name)
        })
      })
	},
    aaa () {
    
    
      this.arr1=[]
      let qq = this.list.map((item, index) => {
    
    
        return this.fun1(item.id)
      })
      Promise.all(qq).then(value => {
    
    
        this.arr1= value //数据一步到位
      })
    },

3.转成对象数组

    <div v-for="(item, index) in list" :key="index">
      <span> {
   
   { item.name }} </span>
    </div>
	aaa(){
    
    
	  this.arr1=[]
      this.list.forEach(item => {
    
    
        this.arr1.push({
    
     params: item.id})
      })
       this.arr1.forEach((item, index) => {
    
    
        getXX(item.params).then(res => {
    
    
          item.name= res.data.name //数据依次增加,一步到位只会加settimeout,待研究
        })
      })
    },

猜你喜欢

转载自blog.csdn.net/q249859693/article/details/129097659
今日推荐