vue中封裝axios方法


 axios基本配置 使用方法

import axios from 'axios'

// 創建axios實例
const service = axios.create({
  baseURL: process.env.BASE_API, // node環境的不同,對應不同的baseURL
  timeout: 5000, // 請求的超時時間
  //設置默認請求頭,使post請求發送的是formdata格式數據// axios的header默認的Content-Type好像是'application/json;charset=UTF-8',我的項目都是用json格式傳輸,如果需要更改的話,可以用這種方式修改
  // headers: {  
    // "Content-Type": "application/x-www-form-urlencoded"
  // },
  withCredentials: true // 允許攜帶cookie
})

 封裝get和post方法

import axios from 'axios';
const serverconfig = require('../../static/serverconfig.json') // 這個json文件中配置接口根目錄地址

class Axios{
    getUrl(url){
      return `${serverconfig.ApiUrl}${url}`; // 獲取完整的接口地址
    };

 // post 請求
  postServer(opt) {
    const _axios = axios.create({
      timeout: 10000
    });
    let data = {};
    if (opt.data) {
      data = opt.data;
    }
    _axios.post(opt.url, data).then((response) => {
      console.log(response);
      if(response.data.status === 'error'){
       // 這里用layer彈層插件
        layer.open({
          content: 'error:' + response.data.hotelInfo
          ,skin: 'msg'
          ,time: 2 //2秒后自動關閉
        });
        if (opt.onFailed) {
          opt.onFailed(response);
        }
        return;
      }
      if (opt.onSuccess) {
        opt.onSuccess(response);
      }
    }).catch(error => {
      if (opt.onFailed) {
        opt.onFailed(error);
      }
      if (!error.response.data.success) {
        alert(error.response.data.error.message);
        // return;
      }

    });
  }

  // get 請求
  getServer(opt) {
    const _axios = axios.create({
      timeout:10000
    });
    let data = {};
    if (opt.data) {
      data = opt.data;
    }
    _axios.get(opt.url, {params: data}).then((response) => {
      if (opt.onSuccess) {
        opt.onSuccess(response);
      }
    }).catch(error => {
      if (opt.onFailed) {
        opt.onFailed(error);
      }
    });
  }


  setData(opt) {
    let data = {};
    if (opt.data) {
      data = opt.data;
    }
    return data;
  }

}

export default Axios;

封裝接口

hotel.service.js
import Axios from  './axios.service'
const AxiosMethods = new Axios();
    sendQueryServer(opt){
    const data = AxiosMethods .setData(opt);
    const url = AxiosMethods .getUrl('/Home/Query');
    AxiosMethods .postServer({url, data, onSuccess: opt.onSuccess, 
    onFailed: opt.onFailed});
  }
}

頁面調用query.vue

 import HotelServer from "@/service/hotel.service"

const hotelServer = new HotelServer();

methods:{
  _sendQueryServer() {
        const loadingIndex = this.loadingShow()
        hotelServer.sendQueryServer({
          onSuccess: (res) => {
            layer.close(loadingIndex)
            console.log(res)
          },
          onFailed: (res) => {
            layer.close(loadingIndex)
          }
        })
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM