开发实战 - ego商城 - 2 公共方法封装
1 公共方法封装
1.1 request封装
-
封装原因
- 接口域名不固定
- 封装判断正常返回逻辑
-
封装位置
- 全局js文件:uniapp-ego\common\api\request.js
- 位置:uniapp-ego\common\api
-
实现
uni.request()
export default {common: {baseUrl: "http://192.168.1.109:3000/api",data: {},header: {'content-type': 'application/json','content-type': 'application/x-www-form-urlencoded'},method: 'GET',dataType: "json"},request(options = {}) {options.url = this.common.baseUrl + options.url;options.data = options.data || this.common.data;options.header = options.header || this.common.header;options.method = options.method || this.common.method;options.dataType = options.dataType || this.common.dataType;return new Promise((resolve, reject) => {uni.showLoading({title: '加载中'});uni.request({...options,success: (res) => {uni.hideLoading();if (res.statusCode === 200) {resolve(res);} else {reject();}},fail: (err) => {uni.hideLoading();reject(err);}})})}
}
- 替换之前接口
<script>
import $http from "@/common/api/request.js";
export default {methods: {// 请求首页数据__init() {$http.request({ url: "/index_list/data" }).then((res) => {let data = res.data.data;this.topBar = data.topBar;this.newTopBar = this.initData(data);console.log("接口响应:", this.newTopBar[0].data);}).catch((err) => {uni.showToast({title: err || "查询失败,请稍后重试",icon: "none",});});}}
}
</script>
https://gitee.com/abigale1998/project/commit/8f547114f5f32d16da937d1e315fbfeec2114ebe