Vue 3 异步操作:async 和 await 的使用指南
在 Vue 3 中,可以通过在方法前加上 'async' 关键字来定义一个异步方法,然后在方法内部使用 'await' 关键字来等待一个异步操作的结果。
下面是一个使用 'async' 和 'await' 的简单示例:
export default {
data() {
return {
result: ''
}
},
methods: {
async fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
this.result = data;
} catch (error) {
console.error(error);
}
}
}
}
在这个示例中,'fetchData' 方法使用 'async' 关键字标记为异步方法。在方法内部,我们使用 'await' 关键字等待 'fetch' 函数返回的结果,然后使用 'await' 关键字等待 'response.json()' 方法返回的结果。最后,将获取到的数据赋值给 'result' 属性。
需要注意的是,'await' 关键字只能在 'async' 函数内部使用,因此在 Vue 组件中,需要将对应的方法定义为 'async' 函数,并在需要等待异步操作结果的地方使用 'await' 关键字。
原文地址: https://www.cveoy.top/t/topic/o25c 著作权归作者所有。请勿转载和采集!