请求方法封装
为了减少代码的冗余,优化代码的可读性,及可维护性,进行请求方法的封装
目录结构
实现流程
一、定义公共http请求方法
创建fetch.js导出一个封装好的promise对象(这里用的是云对象)
fetch.js
/**
* @description: 公共的http请求方法
* @param {String} objectName 云对象名称
* @param {String} methodName 云对象内的方法名称
* @return {Promise} 接口数据
* @example 调用示例
* const res = await http('home','getLabel')
*/
export default async (objectName,methodName) => {
try {
// 显示loading
// uni.showLoading()
// 导入云对象
const cloudObj = uniCloud.importObject(objectName);
// 云对象方法调用
const res = await cloudObj[methodName]();
// 请求成功后的逻辑
if (res.code === 0) {
return res.data;
} else {
uni.showToast({
icon: "none",
title: res.msg || '请求错误'
})
}
// 关闭loading
// uni.hideLoading()
} catch (err) {
uni.showToast({
icon: "none",
title: err.message
})
}
}
二、创建接口文件进行公共方法的调用
label.js
三、导出所有接口方法,并挂载到全局,供每个界面进行使用
- 将所有接口方法保存到一个对象里导出
vue2(webpack) 使用
require.contextvue3(vite) 使用
import.meta.glob
index.js
/**
* @description 批量进行文件导出
*/
const modules = import.meta.glob('./**/*.js',{ eager: true })
const methods = {};
for (const path in modules) {
Object.assign(methods,modules[path])
}
export default methods
- main.js进行方法挂载
vue2 可以使用
Vue.prototype挂载vue3 使用
provide+inject的方式
四、页面/组件内部进行方法的调用
const $http = inject('$http')
label.value = await $http.getLabel()