Vue3如何处理异步操作

Vue3中可以使用async/await和Promise来处理异步操作。

  1. async/await:异步函数返回一个Promise对象,使用async关键字标记函数为异步函数,使用await关键字等待异步操作的完成。例如:
async function getData(){
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()
  return data
}

export default{
  data(){
    return{
      data: null
    }
  },
  async created(){
    this.data = await getData()
  }
}
  1. Promise:使用Promise对象的then()方法来处理异步操作的结果。例如:
export default{
  data(){
    return{
      data: null
    }
  },
  created(){
    fetch('https://api.example.com/data')
      .then(res => res.json())
      .then(data => this.data = data)
  }
}

需要注意的是,在Vue3中,推荐使用setup()函数来替代Vue2中的created()函数,使用异步函数时也要在setup()里使用async关键字标记。例如:

import { ref } from 'vue'

async function getData(){
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()
  return data
}

export default{
  setup(){
    const data = ref(null)
    getData().then(d => data.value = d)
    return {
      data
    }
  }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值