Vue3 集成 Axios 发送 AJAX 请求(九)

在现代前端开发中,Vue3 是一个非常流行的框架,而 Axios 则是一个基于 Promise 的 HTTP 客户端,广泛用于发送 AJAX 请求。本文将详细介绍如何在 Vue3 项目中集成和使用 Axios,包括安装方法、基本请求、参数传递、并发请求等。

什么是 Axios?

Axios 是一个基于 Promise 的 HTTP 客户端,支持浏览器和 Node.js 环境。它具有以下特点:

  • 跨平台:可以在浏览器和 Node.js 中使用。
  • 支持 Promise:所有请求都返回 Promise,方便链式调用和错误处理。
  • 拦截器:可以拦截请求和响应,进行预处理。
  • 取消请求:可以取消正在进行的请求。
  • 自动转换:支持请求和响应数据的自动转换。

GitHub 开源地址:https://github.com/axios/axios

安装 Axios

使用 CDN

如果你的项目不需要打包工具,可以直接通过 CDN 引入 Axios:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

或者使用国内的 CDN:

<script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/axios/0.26.0/axios.min.js" type="application/javascript"></script>

使用 npm

对于使用打包工具的项目,推荐使用 npm 安装:

npm install axios

使用 Bower

如果你还在使用 Bower,可以这样安装:

bower install axios

使用 Yarn

如果你更喜欢 Yarn,可以这样安装:

yarn add axios

基本使用方法

在 Vue3 项目中,首先需要从 Axios 模块中导入默认导出的 axios 对象:

import axios from 'axios';

发起 GET 请求

直接在 URL 中传递参数

axios.get('/user?ID=12345')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error(error);
  });

通过 params 对象传递参数

axios.get('/user', {
  params: {
    ID: 12345
  }
})
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error(error);
  });

使用 async/await

如果你更喜欢使用 async/await,可以在外部函数/方法中添加 async 关键字:

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

发起 POST 请求

axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error(error);
  });

并发执行多个请求

有时候我们需要同时发送多个请求,并在所有请求完成后处理结果。Axios 提供了 axios.all 和 axios.spread 方法来实现这一点:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread((acct, perms) => {
    // 两个请求现在都执行完成
  }));

浏览器支持情况

Axios 支持所有现代浏览器,包括 IE11。如果你需要支持更老的浏览器,可以考虑使用 polyfill。

GET 方法示例

我们可以通过 GET 请求从服务器获取 JSON 数据,并将其显示在 Vue3 组件中:

<div id="app">

<h1>网站列表</h1>
  <div v-for="site in info">
    {{ site.name }}
  </div>
</div>
const app = {
  data() {
    return {
      info: 'Ajax 测试!!'
    }
  },
  mounted() {
    axios.get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => {
        this.info = response.data.sites;
      })
      .catch(error => {
        console.error(error);
      });
  }
};

Vue.createApp(app).mount('#app');

传递参数

GET 请求可以通过两种方式传递参数:

  • 直接在 URL 中添加参数

    axios.get('/user?ID=12345')
      .then(response => {
    
        console.log(response);
      })
      .catch(error => {
        console.error(error);
      });
  • 通过 params 对象传递参数

    axios.get('/user', {
      params: {
        ID: 12345
      }
    })
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.error(error);
      });

POST 方法示例

POST 请求通常用于发送表单数据到服务器:

const app = {
  data() {
    return {
      info: null
    }
  },
  mounted() {
    axios.post('https://www.runoob.com/try/ajax/demo_axios_post.php')
      .then(response => {
        this.info = response;
      })
      .catch(error => {
        console.error(error);
      });
  }
};

Vue.createApp(app).mount('#app');

传递参数

POST 请求可以通过 data 对象传递参数:

axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error(error);
  });

Axios API

Axios 提供了一个灵活的 API,可以通过传递配置对象来创建请求:

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

请求方法的别名

为了方便使用,Axios 为所有支持的请求方法提供了别名:

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

并发请求

处理并发请求的助手函数:

axios.all(iterable)
axios.spread(callback)

创建实例

可以使用自定义配置新建一个 Axios 实例:

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

实例方法

以下是可用的实例方法:

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])

请求配置项

下面是创建请求时可用的配置选项:

{
  // `url` 是用于请求的服务器 URL
  url: "/user",

  // `method` 是创建请求时使用的方法
  method: "get", // 默认是 get

  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL
  baseURL: "https://some-domain.com/api/",

  // `transformRequest` 允许在向服务器发送前,修改请求数据
  transformRequest: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],

  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],

  // `headers` 是即将被发送的自定义请求头
  headers: {"X-Requested-With": "XMLHttpRequest"},

  // `params` 是即将与请求一起发送的 URL 参数
  params: {
    ID: 12345
  },

  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: "brackets"});
  },

  // `data` 是作为请求主体被发送的数据
  data: {
    firstName: "Fred"
  },

  // `timeout` 指定请求超时的毫秒数
  timeout: 1000,

  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // 默认的

  // `adapter` 允许自定义处理请求,以使测试更轻松
  adapter: function (config) {
    /* ... */
  },

  // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  auth: {
    username: "janedoe",
    password: "s00pers3cret"
  },

  // `responseType` 表示服务器响应的数据类型
  responseType: "json", // 默认的

  // `xsrfCookieName` 是用作 xsrf token 的值的 cookie 的名称
  xsrfCookieName: "XSRF-TOKEN", // 默认的

  // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
  xsrfHeaderName: "X-XSRF-TOKEN", // 默认的

  // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },

  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  }
}

总结

通过本文,我们详细介绍了如何在 Vue3 项目中使用 Axios 进行 AJAX 请求。Axios 的强大功能和灵活性使其成为处理 HTTP 请求的理想选择。无论是简单的 GET 请求还是复杂的并发请求,Axios 都能轻松应对。希望本文对你有所帮助,祝你在前端开发的道路上越走越远!