一、vue的实例属性$options。
vue的实例属性$options是用来获取定义在data外的数据和方法的。
二、
在每个模块定义自己的api 文件
vue 中引用
<script>
import xxxapi from './xxxapi';
export default{
api: [xxxapi],
data(){
return {
}
},
methods: {
a(){
this.$api.getList().then(res => res)
}
}
};
</script>
xxxapi.js文件
export default{
getList(){
xxxxxxx// 掉接口,处理函数
}
}
三、 在plugins 的文件夹下
定义api.js
function checkExistedFunction(ret, name) {
if (Object.hasOwnProperty.call(ret, name)) {
console.warn(`Function: ${
name} existed`);
}
}
const MyPlugin = {
install(Vue) {
Vue.mixin({
created() {
const that = this;
const functions = this.$options.api;
if (functions !== undefined) {
const ret = {
};
if (Array.isArray(functions)) {
functions.forEach((mod) => {
Object.getOwnPropertyNames(mod).forEach((key) => {
checkExistedFunction(ret, key);
if (typeof mod[key] === 'function') {
ret[key] = mod[key].bind(that);
}
});
});
this.$api = ret;
} else {
Object.getOwnPropertyNames(functions).forEach((key) => {
checkExistedFunction(ret, key);
if (typeof functions[key] === 'function') {
ret[key] = functions[key].bind(that);
}
});
}
this.$api = ret;
}
},
});
},
};
export default MyPlugin;