当前位置:  首页>> 技术小册>> Vue面试指南

在Vue项目中,通常会使用axios库来进行HTTP请求。为了方便统一管理和使用axios,我们可以封装一个axios实例,并通过Vue的原型将其注入到全局中。

下面是一个简单的封装示例:

  1. // api.js
  2. import axios from 'axios';
  3. const instance = axios.create({
  4. baseURL: 'http://api.example.com',
  5. timeout: 10000,
  6. });
  7. // 请求拦截器
  8. instance.interceptors.request.use(
  9. (config) => {
  10. // 添加token等公共请求头
  11. config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
  12. return config;
  13. },
  14. (error) => {
  15. return Promise.reject(error);
  16. }
  17. );
  18. // 响应拦截器
  19. instance.interceptors.response.use(
  20. (response) => {
  21. return response.data;
  22. },
  23. (error) => {
  24. return Promise.reject(error);
  25. }
  26. );
  27. export default instance;

这里我们使用axios的create方法创建了一个axios实例,并设置了一些默认的配置项,比如基础URL和超时时间。然后我们通过请求拦截器和响应拦截器来统一处理请求和响应,添加一些公共的请求头、处理错误等。

接下来我们可以在Vue的原型中注册这个axios实例,这样就可以在组件中直接使用this.$http来发送请求了。

  1. // main.js
  2. import Vue from 'vue';
  3. import api from './api';
  4. Vue.prototype.$http = api;
  5. 这样我们就完成了一个简单的axios封装。在组件中使用的时候,可以像下面这样调用:
  6. javascript
  7. Copy code
  8. // 在组件中发送GET请求
  9. this.$http.get('/users').then((response) => {
  10. console.log(response);
  11. });
  12. // 在组件中发送POST请求
  13. this.$http.post('/users', { name: '张三', age: 18 }).then((response) => {
  14. console.log(response);
  15. });

这种封装方式可以提高开发效率,也方便了后期的维护和管理。


该分类下的相关小册推荐: