vue3调用asynci和await的 axios
在Vue 3中使用axios的示例代码如下:
首先,安装axios:
npm install axios
然后,在Vue组件中引入axios:
import axios from 'axios';
接下来,可以在Vue组件的方法中使用async/await调用axios:
export default {
methods: {
async fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
}
}
在上面的示例中,我们定义了一个名为fetchData的方法,该方法使用async/await来异步地发送GET请求并处理响应。在成功时,我们打印响应数据;在错误时,我们打印错误信息。
请注意,axios.get方法返回一个Promise对象,因此我们可以使用await关键字来等待其完成。
在Vue组件中调用fetchData方法即可触发请求:
<template>
<button @click="fetchData">Fetch Data</button>
</template>
当用户点击"Fetch Data"按钮时,将调用fetchData方法并发送GET请求。
希望以上信息对你有帮助
原文地址: https://www.cveoy.top/t/topic/hAje 著作权归作者所有。请勿转载和采集!