1. 在 setup 中使用 async/await
<script setup>
import { ref, onMounted } from 'vue'
let loading:boolean=ref(false)
let data = ref(null)
let error:string = ref("")
// 异步函数获取数据
const fetchData = async () => {
loading.value=true;
try {
const response = await fetch(url)
if (!response.ok) {
//失败的
}
data.value =response.data;
} catch (err) {
error.value = err.message
} finally {
loading.value = false
}
}
// 组件挂载后调用
onMounted(() => {
fetchData()
})
</script>
2.使用 Promise.then/catch
<script setup>
import { ref, onMounted } from 'vue'
const loading:boolean = ref(true)
const data = ref(null)
onMounted(() => {
fetch(url)
.then(response => response.json())
.then(data => {
data.value = data
})
.catch(err => {
console.error('获取数据失败:', err)
})
.finally(() => {
loading.value = false
})
})
</script>
3. 多个并行异步操作Promise.all
<script setup>
import { ref, onMounted } from 'vue'
const loading:boolean = ref(true)
const user = ref(null)
const orders = ref(null)
const error:string = ref(null)
onMounted(async () => {
try {
// 并行执行多个异步操作
const [userResponse, ordersResponse] = await Promise.all([
fetch(url1),
fetch(url2)
])
if (!userResponse.ok || !ordersResponse.ok) {
throw new Error('获取数据失败')
}
user.value = userResponse.data
orders.value =ordersResponse.data
} catch (err) {
error.value = err.message
} finally {
loading.value = false
}
})
</script>