axios

安装

npm install axios

main.js

//引入
import axios from 'axios'
//挂载到原型链
Vue.prototype.$http = axios

使用

// 获取模块
getModules(){
   this.$http.get('/warn/module' ).then((json) => {
      if (json.success == true) {
          this.modules = json.data;
       } else {
          this.$message(json.errorMsg);
       }
   }) 
}
//消除告警
 cancelAlarm(){
      this.$http.get('/warn/remove',{
      params:{
          reason:this.reason,
          id:this.alarmId
      }
       }).then((json) => {
          if (json.success == true) {
                  this.$message('消除成功!');
           } else {
                  this.$message(json.errorMsg);
            }
     }) 
}

并发请求。注意返回的是promise对象才可以喔

 //并发请求,并用spread方法拆分
getTest(){
  this.$http.all([this.getModules(),this.getTypes()]).then( 
  this.$http.spread((res1,res2)=>{
  console.log(res1)
  console.log(res2)
  }))
},

拦截器

axios.interceptors.request.use((config) => {
    //拦截之前做的事
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config.url = config.url;
    return config;
},(error)=>{
    //请求错误做的事
    return Promise.reject(error);
});
原文地址:https://www.cnblogs.com/PeriHe/p/9648129.html