[前端系列第8弹]Vue+axios: 一篇文章,讲完axios所有知识

        Vue是一个渐进式的JavaScript框架,它可以让你用简洁的语法创建用户界面和交互逻辑。但是,如果你想要开发一个完整的Web应用,你还需要能够与后端服务器进行数据交互,比如获取数据、发送数据、更新数据或删除数据。这时候,你就需要用到一个HTTP客户端库,来帮助你发送异步请求和处理响应。

        在这篇文章中,我将介绍一个非常流行和实用的HTTP客户端库——axios,它可以让你在Vue中轻松地实现数据交互的功能。我将展示axios的基本概念和用法,以及它与Vue之间的关系和区别。我还将给一些实际的示例,来演示如何用axios来获取数据、发送数据、更新数据和删除数据。最后,告诉你如何在axios中处理错误和取消请求。


目录

一、什么是axios

二、如何安装axios

三、axios的API和便捷方法

四、如何在Vue中使用axios?

(一)直接在组件中导入并使用axios

(二)在原型上绑定axios

(三)使用vue-axios插件

五、如何用axios获取数据?

六、如何用axios发送数据?

七、如何用axios更新数据?

八、如何用axios删除数据?

九、如何用axios处理错误?

十、如何用axios取消请求?

 十一、Vue和axios的最佳实践


一、什么是axios

axios是一个基于Promise的HTTP客户端库,它可以在浏览器和node.js中使用,它可以让你轻松地发送异步请求和处理响应。axios具有以下优点:

  • 支持浏览器和node.js
  • 支持Promise API
  • 支持拦截请求和响应
  • 支持转换请求和响应数据
  • 支持取消请求
  • 支持自动转换JSON数据
  • 支持客户端防御XSRF

axios是一个独立的库,它不依赖于任何其他库或框架,所以你可以在任何地方使用它。但是,如果你想要在Vue中使用axios,你需要做一些额外的配置和封装,来让它更好地与Vue集成。

二、如何安装axios

安装axios有两种方式,一种是通过npm或yarn来安装,另一种是通过CDN链接来引入。如果你使用的是Vue CLI创建的项目,那么你可以使用第一种方式来安装axios。只需要在项目根目录下运行以下命令:

npm install axios --save
# 或者
yarn add axios

这样就会将axios添加到你的项目依赖中,并且可以在任何地方导入并使用它。

如果你没有使用Vue CLI创建项目,或者你只想要快速地测试一下axios的功能,那么你可以使用第二种方式来引入axios。只需要在你的HTML文件中添加以下标签:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

这样就会从CDN链接加载并执行axios的代码,并且可以在全局变量window上访问到axios对象。

三、axios的API和便捷方法

axios提供了一个通用的方法来发送任何类型的HTTP请求:

axios(config)

其中config是一个对象,包含了请求的相关配置信息,如url, method, data, headers等。例如:

// 发送一个POST请求
axios({
  method: 'post',
  url: '/user',
  data: {
    firstName: 'Alice',
    lastName: 'Smith'
  }
});

除了通用方法外,axios还提供了一些便捷方法来发送特定类型的HTTP请求:

// 发送一个GET请求(默认方法)
axios(url[, config])

// 发送一个GET请求,并传递查询参数
axios.get(url[, config])

// 发送一个POST请求,并传递请求体数据
axios.post(url[, data[, config]])

// 发送一个PUT请求,并传递请求体数据
axios.put(url[, data[, config]])

// 发送一个PATCH请求,并传递请求体数据
axios.patch(url[, data[, config]])

// 发送一个DELETE请求
axios.delete(url[, config])

// 发送一个HEAD请求
axios.head(url[, config])

// 发送一个OPTIONS请求
axios.options(url[, config])

这些便捷方法可以让你更简洁地发送HTTP请求,而无需每次都指定请求方法。例如:

// 发送一个GET请求
axios('/user');

// 等价于
axios({
  method: 'get',
  url: '/user'
});

无论你使用哪种方法发送HTTP请求,axios都会返回一个Promise对象,你可以使用then方法来处理成功的响应,或者使用catch方法来处理失败的响应。例如:

// 发送一个GET请求,并处理响应
axios.get('/user')
  .then(function (response) {
    // 处理成功的响应
    console.log(response);
  })
  .catch(function (error) {
    // 处理失败的响应
    console.log(error);
  });

如果你使用的是ES6的语法,你可以使用箭头函数来简化代码:

// 发送一个GET请求,并处理响应(ES6)
axios.get('/user')
  .then(response => {
    // 处理成功的响应
    console.log(response);
  })
  .catch(error => {
    // 处理失败的响应
    console.log(error);
  });

如果你使用的是ES7的语法,你可以使用async/await来简化代码:

// 发送一个GET请求,并处理响应(ES7)
async function getUser() {
  try {
    const response = await axios.get('/user');
    // 处理成功的响应
    console.log(response);
  } catch (error) {
    // 处理失败的响应
    console.log(error);
  }
}

四、如何在Vue中使用axios?

在Vue中使用axios,有以下几种方式:

  • 直接在组件中导入并使用axios
  • 在原型上绑定axios,使其在所有组件中可用
  • 使用vue-axios插件,将axios集成到Vue实例中

下面我们来看一些具体的示例:

(一)直接在组件中导入并使用axios

这是最简单的方式,你只需要在需要发送请求的组件中导入axios,并调用其方法即可。例如,假设我们有一个UserList组件,它需要从后端获取用户列表并显示在页面上。我们可以这样写:

<template>
  <div>
    <h1>用户列表</h1>
    <ul>
      <li v-for="user in users" :key="user.id">
        {
   
   { user.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
    // 发送GET请求获取用户列表
    axios.get('/user')
      .then(response => {
        // 将响应数据赋值给users
        this.users = response.data;
      })
      .catch(error => {
        // 处理错误
        console.log(error);
      });
  }
};
</script>

这种方式的优点是简单明了,不需要额外的配置。缺点是每次都需要导入axios,并且不能方便地进行全局的拦截或转换。

(二)在原型上绑定axios

这种方式可以让你在所有组件中通过this.$http访问axios,而无需每次都导入。你只需要在创建Vue实例之前,在原型上绑定axios即可。例如,在main.js文件中:

import Vue from 'vue';
import axios from 'axios';

// 在原型上绑定axios
Vue.prototype.$http = axios;

new Vue({
  // ...
});

然后,在任何组件中,你都可以这样使用:

this.$http.get('/user')
  .then(response => {
    // ...
  })
  .catch(error => {
    // ...
  });

这种方式的优点是方便统一管理,不需要重复导入。缺点是可能会造成原型污染,或者与其他库冲突。

(三)使用vue-axios插件

这种方式可以让你在所有组件中通过this.axios或this.$http访问axios,并且可以利用Vue的插件机制进行一些全局配置。你需要先安装vue-axios插件:

npm install vue-axios --save

然后,在创建Vue实例之前,使用Vue.use方法安装插件,并传入axios作为参数。例如,在main.js文件中:

import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

// 使用vue-axios插件
Vue.use(VueAxios, axios);

new Vue({
  // ...
});

然后,在任何组件中,你都可以这样使用:

this.axios.get('/user')
  .then(response => {
    // ...
  })
  .catch(error => {
    // ...
  });

// 或者

this.$http.get('/user')
  .then(response => {
    // ...
  })
  .catch(error => {
    // ...
  });

这种方式的优点是可以更好地与Vue集成,利用Vue的生命周期钩子和响应式系统。缺点是需要额外安装一个插件,或者与其他插件冲突。

五、如何用axios获取数据?

获取数据是Web应用中最常见的数据交互操作,它通常对应于HTTP的GET方法。使用axios获取数据非常简单,只需要调用axios.get方法,并传入请求的URL即可。例如,假设我们有一个UserDetail组件,它需要从后端获取用户的详细信息并显示在页面上。我们可以这样写:

<template>
  <div>
    <h1>用户详情</h1>
    <p>姓名:{
   
   { user.name }}</p>
    <p>年龄:{
   
   { user.age }}</p>
    <p>邮箱:{
   
   { user.email }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {}
    };
  },
  props: {
    userId: {
      type: Number,
      required: true
    }
  },
  mounted() {
    // 发送GET请求获取用户详情
    axios.get(`/user/${this.userId}`)
      .then(response => {
        // 将响应数据赋值给user
        this.user = response.data;
      })
      .catch(error => {
        // 处理错误
        console.log(error);
      });
  }
};
</script>

这里,我们使用了props来接收父组件传递的userId参数,然后拼接到请求的URL中。我们还使用了模板字符串(反引号)来简化字符串的拼接。注意,如果你使用的是ES5的语法,你需要使用字符串连接符(+)来拼接字符串。

当我们发送GET请求时,后端服务器会返回一个响应对象,它包含了以下属性:

  • data: 响应体数据,通常是一个对象或数组
  • status: 响应状态码,如200, 404, 500等
  • statusText: 响应状态文本,如OK, Not Found, Internal Server Error等
  • headers: 响应头信息,如Content-Type, Content-Length等
  • config: 请求的配置信息,如url, method, data, headers等

我们可以在then方法中通过response参数来访问这些属性,并根据需要进行处理。例如,我们可以打印出响应状态码和响应头信息:

axios.get('/user')
  .then(response => {
    // 打印响应状态码和响应头信息
    console.log(response.status);
    console.log(response.headers);
    // ...
  })
  .catch(error => {
    // ...
  });

如果我们只关心响应体数据,我们可以直接使用response.data来访问它,并将其赋值给组件的data属性。例如,我们可以将用户列表赋值给users属性:

axios.get('/user')
  .then(response => {
    // 将响应体数据赋值给users属性
    this.users = response.data;
  })
  .catch(error => {
    // ...
  });

有时候,我们需要在发送GET请求时传递一些查询参数,比如分页、排序、过滤等。我们可以使用params属性来指定查询参数,它是一个对象,包含了键值对。例如,我们可以传递page和size参数来获取第二页的用户列表,每页显示10条数据:

axios.get('/user', {
  params: {
    page: 2,
    size: 10
  }
})
  .then(response => {
    // ...
  })
  .catch(error => {
    // ...
  });

这样,axios会自动将params对象转换为查询字符串,并拼接到URL中,如/user?page=2&size=10。

六、如何用axios发送数据?

发送数据是Web应用中另一个常见的数据交互操作,它通常对应于HTTP的POST, PUT, PATCH或DELETE方法。使用axios发送数据也非常简单,只需要调用相应的方法,并传入请求的URL和数据即可。例如,假设我们有一个UserForm组件,它需要从后端添加或更新用户的信息。我们可以这样写:

<template>
  <div>
    <h1>用户表单</h1>
    <form @submit.prevent="submitForm">
      <label>姓名</label>
      <input v-model="user.name" required>
      <label>年龄</label>
      <input v-model.number="user.age" required>
      <label>邮箱</label>
      <input v-model="user.email" required>
      <button type="submit">提交</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {}
    };
  },
  props: {
    userId: {
      type: Number,
      default: null
    }
  },
  mounted() {
    // 如果有userId参数,说明是更新用户信息,需要先获取用户详情
    if (this.userId) {
      axios.get(`/user/${this.userId}`)
        .then(response => {
          // 将响应数据赋值给user
          this.user = response.data;
        })
        .catch(error => {
          // 处理错误
          console.log(error);
        });
    }
  },
  methods: {
    submitForm() {
      // 如果有userId参数,说明是更新用户信息,需要发送PUT请求
      if (this.userId) {
        axios.put(`/user/${this.userId}`, this.user)
          .then(response => {
            // 处理成功的响应
            console.log(response);
          })
          .catch(error => {
            // 处理失败的响应
            console.log(error);
          });
      } else {
        // 如果没有userId参数,说明是添加用户信息,需要发送POST请求
        axios.post('/user', this.user)
          .then(response => {
            // 处理成功的响应
            console.log(response);
          })
          .catch(error => {
            // 处理失败的响应
            console.log(error);
          });
      }
    }
  }
};
</script>

这里,我们使用了v-model指令来实现表单输入和组件数据的双向绑定。我们还使用了@submit.prevent修饰符来阻止表单的默认提交行为,并调用自定义的submitForm方法来发送请求。

当我们发送POST, PUT, PATCH或DELETE请求时,后端服务器会返回一个响应对象,它与GET请求时返回的响应对象相同,包含了data, status, statusText, headers, config等属性。我们可以在then方法中通过response参数来访问这些属性,并根据需要进行处理。例如,我们可以打印出响应状态码和响应体数据:

axios.post('/user', this.user)
  .then(response => {
    // 打印响应状态码和响应体数据
    console.log(response.status);
    console.log(response.data);
  })
  .catch(error => {
    // ...
  });

如果我们只关心响应状态码,我们可以直接使用response.status来访问它,并根据不同的值进行不同的操作。例如,我们可以根据响应状态码来显示不同的提示信息:

axios.post('/user', this.user)
  .then(response => {
    // 根据响应状态码显示不同的提示信息
    if (response.status === 201) {
      alert('用户添加成功');
        //...
}

七、如何用axios更新数据?

更新数据是Web应用中修改已有数据的操作,它通常对应于HTTP的PUT或PATCH方法。使用axios更新数据和发送数据类似,只需要调用相应的方法,并传入请求的URL和数据即可。区别在于,PUT方法会替换整个资源,而PATCH方法只会修改部分资源。例如,假设我们有一个UserForm组件,它需要从后端更新用户的信息。我们可以这样写:

<template>
  <div>
    <h1>用户表单</h1>
    <form @submit.prevent="submitForm">
      <label>姓名</label>
      <input v-model="user.name" required>
      <label>年龄</label>
      <input v-model.number="user.age" required>
      <label>邮箱</label>
      <input v-model="user.email" required>
      <button type="submit">提交</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {}
    };
  },
  props: {
    userId: {
      type: Number,
      required: true
    }
  },
  mounted() {
    // 发送GET请求获取用户详情
    axios.get(`/user/${this.userId}`)
      .then(response => {
        // 将响应数据赋值给user
        this.user = response.data;
      })
      .catch(error => {
        // 处理错误
        console.log(error);
      });
  },
  methods: {
    submitForm() {
      // 发送PUT请求更新用户信息
      axios.put(`/user/${this.userId}`, this.user)
        .then(response => {
          // 处理成功的响应
          console.log(response);
        })
        .catch(error => {
          // 处理失败的响应
          console.log(error);
        });
    }
  }
};
</script>

这里,我们使用了PUT方法来更新用户信息,它会将整个user对象替换为新的值。如果我们只想要修改用户的部分属性,比如年龄,我们可以使用PATCH方法来更新用户信息,它只会修改指定的属性。例如:

// 发送PATCH请求更新用户年龄
axios.patch(`/user/${this.userId}`, { age: this.user.age })
  .then(response => {
    // 处理成功的响应
    console.log(response);
  })
  .catch(error => {
    // 处理失败的响应
    console.log(error);
  });

这里,我们只传递了一个包含age属性的对象作为请求体数据,它只会修改用户的年龄属性,而不会影响其他属性。

八、如何用axios删除数据?

删除数据是Web应用中移除已有数据的操作,它通常对应于HTTP的DELETE方法。使用axios删除数据也很简单,只需要调用axios.delete方法,并传入请求的URL即可。例如,假设我们有一个UserList组件,它需要从后端删除用户的信息。我们可以这样写:

<template>
  <div>
    <h1>用户列表</h1>
    <ul>
      <li v-for="user in users" :key="user.id">
        {
   
   { user.name }}
        <button @click="deleteUser(user.id)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
    // 发送GET请求获取用户列表
    axios.get('/user')
      .then(response => {
        // 将响应数据赋值给users
        this.users = response.data;
      })
      .catch(error => {
        // 处理错误
        console.log(error);
      });
  },
  methods: {
    deleteUser(userId) {
      // 发送DELETE请求删除用户信息
      axios.delete(`/user/${userId}`)
        .then(response => {
          // 处理成功的响应
          console.log(response);
          // 从users数组中移除该用户
          this.users = this.users.filter(user => user.id !== userId);
        })
        .catch(error => {
          // 处理失败的响应
          console.log(error);
        });
    }
  }
};
</script>

这里,我们使用了deleteUser方法来删除用户信息,它会发送DELETE请求,并传入用户的id作为URL参数。然后,我们还需要从users数组中移除该用户,以保持数据的一致性。我们可以使用filter方法来过滤掉与用户id相同的元素,返回一个新的数组。

九、如何用axios处理错误?

在发送HTTP请求时,可能会遇到各种错误,比如网络错误、服务器错误、客户端错误等。使用axios处理错误也很简单,只需要使用catch方法来捕获异常,并传入一个回调函数来处理错误即可。例如:

axios.get('/user')
  .then(response => {
    // ...
  })
  .catch(error => {
    // 处理错误
    console.log(error);
  });

在catch方法中,我们可以通过error参数来访问错误对象,它包含了以下属性:

  • message: 错误信息,如Network Error, Request failed with status code 404等
  • config: 请求的配置信息,如url, method, data, headers等
  • request: 请求对象,如XMLHttpRequest或http.ClientRequest等
  • response: 响应对象,如data, status, statusText, headers等

我们可以根据不同的属性来判断错误的类型和原因,并进行相应的处理。例如,我们可以根据响应状态码来显示不同的提示信息:

axios.get('/user')
  .then(response => {
    // ...
  })
  .catch(error => {
    // 处理错误
    if (error.response) {
      // 如果有响应对象,说明服务器返回了错误的响应
      switch (error.response.status) {
        case 400:
          alert('请求参数错误');
          break;
        case 401:
          alert('未授权,请登录');
          break;
        case 403:
          alert('拒绝访问');
          break;
        case 404:
          alert('请求地址不存在');
          break;
        case 500:
          alert('服务器内部错误');
          break;
        default:
          alert('未知错误');
      }
    } else if (error.request) {
      // 如果有请求对象,说明请求没有成功发送或没有收到响应
      alert('网络错误,请检查网络连接');
    } else {
      // 如果没有请求对象,说明是其他原因导致的错误
      alert('发生了一些错误,请稍后重试');
    }
  });

十、如何用axios取消请求?

在发送HTTP请求时,有时候我们可能需要取消已经发送的请求,比如用户点击了取消按钮,或者页面跳转了等。使用axios取消请求也很简单,只需要使用CancelToken对象来创建一个取消令牌,并传入请求的配置中即可。例如:

// 创建一个取消令牌源
const source = axios.CancelToken.source();

// 发送一个GET请求,并传入取消令牌
axios.get('/user', {
  cancelToken: source.token
})
  .then(response => {
    // ...
  })
  .catch(error => {
    // 处理错误
    if (axios.isCancel(error)) {
      // 如果是由于取消令牌导致的错误,说明请求已经被取消了
      console.log('Request canceled', error.message);
    } else {
      // 如果是其他原因导致的错误,正常处理
      console.log(error);
    }
  });

// 在某个时机调用取消令牌源的cancel方法来取消请求
source.cancel('Operation canceled by the user.');

这样,当我们调用source.cancel方法时,axios会自动取消请求,并抛出一个错误对象,我们可以通过axios.isCancel方法来判断是否是由于取消令牌导致的错误,然后进行相应的处理。

 十一、Vue和axios的最佳实践

在Vue中使用axios,有以下几个方面需要注意:

  • 封装axios:为了方便管理和维护,我们可以将axios的配置、拦截、转换等功能封装到一个单独的文件中,然后在需要的地方导入并使用。这样可以避免重复的代码,也可以统一处理错误和异常。
  • 使用环境变量:为了适应不同的开发和部署环境,我们可以使用环境变量来配置axios的基础URL、超时时间、请求头等信息。这样可以避免硬编码,也可以灵活地切换不同的环境。
  • 使用模块化:为了提高代码的可读性和可维护性,我们可以将不同的业务逻辑分离到不同的模块中,然后在需要的地方导入并使用。这样可以避免混乱,也可以方便地复用和扩展。
  • 使用async/await:为了简化异步代码的编写和阅读,我们可以使用async/await语法来替代Promise链式调用。这样可以避免回调地狱,也可以更好地处理错误和异常。

下面我们来看一个简单的示例,如何在Vue中使用axios的最佳实践:

首先,我们创建一个axios.js文件,用来封装axios的配置、拦截、转换等功能:

// 导入axios
import axios from 'axios';

// 创建一个axios实例
const instance = axios.create({
  // 使用环境变量来配置基础URL
  baseURL: process.env.VUE_APP_BASE_URL,
  // 使用环境变量来配置超时时间
  timeout: process.env.VUE_APP_TIMEOUT,
  // 使用环境变量来配置请求头
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.VUE_APP_TOKEN}`
  }
});

// 添加请求拦截器
instance.interceptors.request.use(config => {
  // 在发送请求之前做些什么,比如添加加载动画
  console.log('开始发送请求');
  return config;
}, error => {
  // 对请求错误做些什么,比如提示错误信息
  console.log('请求失败');
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(response => {
  // 对响应数据做点什么,比如移除加载动画
  console.log('接收到响应');
  return response;
}, error => {
  // 对响应错误做点什么,比如提示错误信息
  console.log('响应失败');
  return Promise.reject(error);
});

// 导出封装好的axios实例
export default instance;

然后,我们创建一个user.js文件,用来封装用户相关的业务逻辑:

// 导入封装好的axios实例
import axios from './axios';

// 定义一个获取用户列表的方法
export const getUserList = async () => {
  try {
    // 使用async/await语法来发送GET请求,并处理响应
    const response = await axios.get('/user');
    // 返回响应数据
    return response.data;
  } catch (error) {
    // 处理错误
    console.log(error);
    // 抛出异常
    throw error;
  }
};

// 定义一个添加用户的方法
export const addUser = async user => {
  try {
    // 使用async/await语法来发送POST请求,并处理响应
    const response = await axios.post('/user', user);
    // 返回响应数据
    return response.data;
  } catch (error) {
    // 处理错误
    console.log(error);
    // 抛出异常
    throw error;
  }
};

// 定义一个更新用户的方法
export const updateUser = async (userId, user) => {
  try {
    // 使用async/await语法来发送PUT请求,并处理响应
    const response = await axios.put(`/user/${userId}`, user);
    // 返回响应数据
    return response.data;
  } catch (error) {
    // 处理错误
    console.log(error);
    // 抛出异常
    throw error;
  }
};

// 定义一个删除用户的方法
export const deleteUser = async userId => {
  try {
    // 使用async/await语法来发送DELETE请求,并处理响应
    const response = await axios.delete(`/user/${userId}`);
    // 返回响应数据
    return response.data;
  } catch (error) {
    // 处理错误
    console.log(error);
    // 抛出异常
    throw error;
  }
};

最后,我们在需要的组件中导入并使用user.js文件中的方法,比如UserList组件:

<template>
  <div>
    <h1>用户列表</h1>
    <ul>
      <li v-for="user in users" :key="user.id">
        {
   
   { user.name }}
        <button @click="deleteUser(user.id)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script>
// 导入用户相关的方法
import { getUserList, deleteUser } from './user';

export default {
  data() {
    return {
      users: []
    };
  },
  async mounted() {
    // 使用async/await语法来获取用户列表,并赋值给users属性
    this.users = await getUserList();
  },
  methods: {
    async deleteUser(userId) {
      // 使用async/await语法来删除用户,并从users数组中移除该用户
      await deleteUser(userId);
      this.users = this.users.filter(user => user.id !== userId);
    }
  }
};
</script>

这样,我们就使用了Vue和axios的最佳实践,使得我们的代码更加简洁、清晰、可读、可维护和可扩展。

本文到这里就结束了,你学废了吗~

猜你喜欢

转载自blog.csdn.net/TaloyerG/article/details/132388814
今日推荐