vue--配套axios用法

8,049 阅读2分钟

vue官方早就推荐axios,抛弃vue-resource。

axios常规用法

安装: npm install axios

栗子:

1.GET 请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(response=>{
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
//换个姿势实现
axios.get('/user', {
    params: {                         //区别:  get是用params传值
      ID: 12345
    }
  })
  .then(response=>{
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

2.POST 请求

axios.post('/user', {                  //        post是用对象传值      
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(response=>{
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

3.执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {      //两个参数分别代表返回的结果
                                                   // 当这两个请求都完成的时候会触发这个函数
  }));

axios -API

axios(config) //传配置,建请求{config},完整的包含then和catch

// 发送 POST 请求
axios({                                            //配置好一个对象,传递进去
  method: 'post',
  url: '/user/12345',
  data: {0
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

// 发送 GET 请求(默认的方法)
axios('/user/12345');

请求方法-别名列表

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)//iterable是一个可以迭代的参数如数组等
axios.spread(callback)//callback要等到所有请求都完成才会执行

实例

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

实例--全局默认配置

axios.defaults.baseURL = 'http://api.exmple.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';

实例--自定义默认配置

var instance = axios.create({ baseURL: 'https://api.example.com' }); //创建

instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;//修改


响应结构

axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

拦截器----这货很有用

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

// 添加请求拦截器
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);
  });

移除拦截器

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);


---------------------------------来势汹汹的分割线------------------------------------------


整理些有用的实现例子

栗子1:封装到vue原型上使用

import axios from 'axios'

Vue.prototype.$http= axios
 methods: {
    show() {
      this.$http({
        method: 'get',
        url: '/class',
        data: {
          name: 'liu'
        }
     })
  }

------------------------------------------------------------------------------------------

栗子2

import axios from 'axios'
// 超时时间
axios.defaults.timeout = 13000;
//跨域请求,允许保存cookie
axios.defaults.withCredentials = true;
//错误提示信息
let msg='服务器被外星人拉走了';
let loadinginstace;                                //提示控件
//http请求拦截
axios.interceptors.request.use(config=>{
                                                   //服务器请求中动画
  loadinginstace=Loading.service({
    fullscreen: true
  });
  //配置token后期会改
  //config.headers['X-token'] = getToken();         //做些配置处理
  return config                                     //返回配置
},err=> {                                           //请求失败处理      
  //打印错误
  loadinginstace.close();
  Message.error({
    message: '加载超时'
  });
  return Promise.reject(err);
});
                                                    //http 响应拦截
axios.interceptors.response.use(data=>{
  loadinginstace.close();
  return data
},err=>{                                            //响应失败处理
  loadinginstace.close();
  Message.error({
    message:msg
  });
  return Promise.reject(err);
});

export default axios



一个老铁二次封装的例子:

https://segmentfault.com/a/1190000012332982