在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>
标签:function,arr,axios,封装,name,url,ob,Vue,data
From: https://www.cnblogs.com/whoelse/p/18133420