VUE中使用 async await 将 axios 异步请求同步化处理

1211dsa大飒飒撒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒飒

axios常规用法

export default {
  name: 'Historys',
  data() {
    return { 
      totalData: 0,  
      tableData: []
    }
  },
  created () {
    // 1.进入后先加载一次数据
    this.getHistoryData()
  },
  methods: { 
    // 2.点击时加载数据  
    handleClick (tab) {
      let data = {
        status: tab.name,
      }
      this.getHistoryData(data)
    },
    // 统一处理axios请求
    getHistoryData (data) { 
      axios.get('/api/survey/list/', {
        params: data
      }).then((res) => {
        this.tableData = res.data.result
        this.totalData = res.data.count
      })
    }
  }
}

使用 asyns/await 将 axios 异步请求同步化:

  • 当 axios 请求拿到的数据在不同场景下做相同的处理时:
export default {
  name: 'Historys',
  data() {
    return { 
      totalData: 0,  
      tableData: []
    }
  },
  created () {
    this.getHistoryData()
  },
  methods: { 
    handleClick (tab) {
      let data = {
        status: tab.name,
        name: this.formInline.user,
        cid: this.formInline.identity,
        start_time: this.formInline.dateTime 
        end_time: this.formInline.dateTime
      }
      this.getHistoryData(data)
    },
    // 统一处理axios请求
    async getHistoryData (data) {
      try {
        let res = await axios.get('/api/survey/list/', {
          params: data
        })
        this.tableData = res.data.result
        this.totalData = res.data.count
      } catch (err) {
        console.log(err)
        ert('请求出错!')
      }
    }
  }
}
posted @ 2019-04-13 12:13  仲吕  阅读(408)  评论(0编辑  收藏  举报