1、项目更目录下新建common文件夹,再创建request.js文件
2、打开request.js文件,开始写封装的代码
const request = (url = '', date = {}, titles = '加载中',type = 'POST', header = { }) => { return new Promise((resolve, reject) => { uni.showLoading({ title: titles }); uni.request({ method: type, url: url, data: date, header: header, dataType: 'json', }).then((response) => { uni.hideLoading(); uni.stopPullDownRefresh(); let [error, res] = response; if(res.data.code == 0){ uni.showToast({ title:res.data.msg, duration: 1000, success:function(){ uni.hideLoading(); } }); setTimeout(function () { resolve(res.data); }, 1000); }else if(res.data.code == 1){ uni.showToast({ title:res.data.msg.MSG, image:'../../static/public/guanbi_i.png', duration: 2000, success:function(){ uni.hideLoading(); } }); }else { uni.showToast({ title:res.data.msg, image:'../../static/public/guanbi_i.png', duration: 2000, success:function(){ uni.hideLoading(); } }); } }).catch(error => { uni.hideLoading(); uni.stopPullDownRefresh(); let [err, res] = error; reject(err) }) }); } export default request
3、在main.js全局注册
import request from 'common/request.js' Vue.prototype.$request = request
4、页面调用
this.$request('url地址', { //参数放在这里 'id':1, }).then(res => { // 打印调用成功回调 console.log('返回正确回调') })