安装


 使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 cdn:

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

 

用法


 在main.js文件中,配置axios

//引入axios
import Axios from 'axios';

//将 axios 改写为 Vue 的原型属性
Vue.prototype.$axios = Axios;

在 main.js 中添加了这两行代码之后,就可以直接在组件的 created 钩子中使用 $axios 命令

created() {
            this.$axios.post('https://www.easy-mock.com/mock/5b23687cf3c9fb2931a37f69/example')
                .then(res => {
                    console.log(res.data);
                })
                .catch(error => {
                    console.log(error);
                })
        }

 

拦截器


在请求或响应被 then 或 catch 处理前拦截它们。

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

 

相关文章:

  • 2021-07-13
  • 2021-10-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-02
  • 2022-02-12
  • 2021-09-26
  • 2022-12-23
  • 2022-01-05
相关资源
相似解决方案