基于Vue2 的axios简单封装

在static/mock下建一个模拟数据文件 json1.json

{
  "a1": 123,
  "a2": 567
}

在文件目录下新建 src/utlis/http.js


//src/utlis/http.js
import axios from "axios";
export default (function() {
  function qa(arr) {
    let _iqaob = new _iqa(),
      _urlarr = arr || [];
    arr.forEach((item, i) => {
      let _name = qa.getPathname(_urlarr[i]);
      (function(url) {
        _iqaob[_name] = function(ob) {
          _iqaob.sendMes.call(_iqaob, url, ob);
        };
      })(_urlarr[i]);
    });

    return _iqaob;
  }
  function _iqa() {
    this._vueob = {};
    this.statue = 0;
  }
  // 发送请求
  _iqa.prototype.sendMes = function(url, ob) {
    console.log("console", this, url, ob);
    let self = this,
      _url = url || "",
      _ob = ob || {},
      _type = _ob.type || "get",
      _data = _ob.data || {},
      _isblock = _ob.isblock || true, //是否阻塞()
      callback =
        _ob.callback ||
        function() {
          console.log("callback is  undefined");
        };

    let status = {
      get: function() {
        let _quary = qa.qs(_data);
        axios.get(_url + _quary).then(function(res) {
          const _name = qa.getPathname(_url);
          const result = callback.call(self._vueob, res);
          if (result) {
            self._vueob[_name] = result;
          } else {
            self._vueob[_name] = res.data;
          }
        });
      },
      post: function() {},
      put: function() {},
      delete: function() {}
    };

    //这里判断控制是否可以重复提交
    if (self.statue == 0 || !_isblock) {
      if (_isblock) {
        self.statue = 1;
      }
      status[_type]();
    } else {
      status[_type]();
    }
  };

  _iqa.prototype.v = function(vueob) {
    this._vueob = vueob;
    return this;
  };

  //获取接口名
  qa.getPathname = function(url) {
    let _arr = url.split("/"),
      _name = _arr[_arr.length - 1],
      _newname = _name.split(".")[0];
    return _newname;
  };

  //参数序列化
  qa.qs = function(data) {
    let _str = "",
      _len = 0;
    if (JSON.stringify(data) != "{}") {
      _str += "?";
    }
    for (var item in data) {
      if (_len != 0) {
        _str += "&";
      }
      _str += item;
      _str += "=";
      _str += data[item];
      _len++;
    }
    return _str;
  };

  return qa;
})();

//main.js
const files = require.context("../static/mock", true, /\.json$/);
let arr = [];
files.keys().forEach(key => {
  arr.push("./static/mock/" + key.replace(/(\.\/)/g, ""));
});

// * Axios
import http from "./utils/http.js";
Vue.prototype.http = http(arr);
console.log("console", Vue.prototype.http);

在 HelloWorld.vue 文件中

 //HelloWorld.vue 
<template>
  <div class="hello">
    <pre>{{ json1 }}</pre>
    <!-- <Com1/>
    <Com2/> -->
    <router-link to="./com1">com1</router-link>
    <router-link to="./com2">com2</router-link>

    <!-- 按钮根据value -->
    <div v-permission="'10'">
      <button>权限1</button>
    </div>
    <div v-permission="'5'">
      <button>权限2</button>
    </div>

    <router-view />
  </div>
</template>


<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      json1: ""
    };
  }, 
  mounted() {
  //这里调用axiox
    this.http.v(this).json1({
      data: { a: 1, b: 1 },
      callback: function(res) {
       return res.data.a1
      }
    });
  },
  methods: {}
};
</script>
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

同时欢迎大家进群一起交流学习:

在这里插入图片描述

  • 14
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值