在 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/o25k 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录