文件的层级展示
-
创建http.js文件,导出一个封装好的promise对象(内部进行uniCloud调用)
export default ({name,data={}})=> { /* 导出pormise对象 */ return new Promise((resolve,reject) => { uni.showLoading({ }) uniCloud.callFunction({ name, success({result}) { if(result.code === 0) { resolve(result.data) }else { uni.showToast({icon:"none",title:result.msg}) } }, fail(err) { reject(err) }, complete() { uni.hideLoading() } }) }) }
二、创建接口文件进行公共方法的调用
使用webpack中的require.context方法对所有请求函数进行收集
一个webpack的api,通过执行require.context函数获取一个特定的上下文,主要用来实现自动化导入模块,在前端工程中,如果遇到从一个文件夹引入很多模块的情况,可以使用这个api,它会遍历文件夹中的指定文件,然后自动导入,使得不需要每次显式的调用import导入模块
/* 批量进行文件导出 */
// . =>API目录的相对路径
// true => 是否查询子目录
// /.js/ => 需要查询的文件的后缀名
const requireApi = require.context('.', true, /.js$/);
console.log(requireApi.keys())
let module = {};
requireApi.keys().forEach((key, index) => {
if (key === './index.js') return
Object.assign(module, requireApi(key))
})
export default module
-
main.js进行方法挂载
import module from './ajax/api/index.js' Vue.prototype.$http = module;
四、页面/组件内部进行方法的调用
async _intiLabelList() {
const labelList = await this.$http.get_label_list()
console.log(labelList )
}
文件目录结构