封装一些常用方法,如网络请求等:
封装后的效果:
var that=this;
var parm={
userToekn:xxxxxx
};
that.api.RefashByBar(parm).then(res => {
that.webData=res;
})
效果:
- 在需要http的地方,仅需api.xxxx就能点出来
- 不关心返回后异常,仅需关心成功的结果
- 不同的异常情况,在utils中已处理好
封装一个js文件,叫https.js:
let RefashByCard= (data) => {
return new Promise((resolve, reject) => {
resolve(apiRequest("https://www.xxxxxxxx.com/Refash/RefashByCard", data))
})
}
let RefashByBar= (data) => {
return new Promise((resolve, reject) => {
resolve(apiRequest("https://www.xxxxxxxx.com/Refash/RefashByBar", data))
})
}
const apiRequest = (url, data, header) => {
let promise = new Promise(function(resolve, reject) {
uni.showLoading({
title: '加载中',
mask: true
})
uni.request({
url: url,
data: data ? data : null,
method: 'POST',
header: header ? header : {
'content-type': 'application/x-www-form-urlencoded'
},
success: function(res) {
console.log(res)
var ans=res.data;
uni.hideLoading()
if(ans.code==0){
uni.showModal({
content: "服务器繁忙,请稍后再试",
showCancel: false,
confirmText: '确定',
confirmColor: '#1E90FF'
})
}else if(ans.code==2){
uni.showModal({
content: ans.data,
showCancel: false,
confirmText: '确定',
confirmColor: '#1E90FF'
})
}else{
resolve(ans.data);
}
},
fail: function(res) {
console.log(res);
uni.hideLoading();
uni.showModal({
content: "服务器繁忙,请稍后再试",
showCancel: false,
confirmText: '确定',
confirmColor: '#1E90FF',
success: res999 => {
if (res999.confirm) {
uni.navigateBack({
delta: 1
})
}
}
})
}
})
});
return promise;
}
export default{
RefashByBar,
RefashByCard,
......
}
备注:
- apiRequest 也可以写多个,apiRequest 1,apiRequest 2,…
- 看情况,这里根据后端的code标识来走
- 可提示繁忙,可提示后端文案,可返回页面
- 效果自己搭配
在main.js中全局引用https.js,即可在工程中随意用:
import https from 'pages/utils/web/https.js';
Vue.prototype.api = https
同理,在main.js中,可以封装一些其他的东西:
如uni的model对话框
//在业务页面中这样用
//对话框,仅提示
that.Toast0('仅店铺管理员可使用此功能');
//对话框,提示后,绑定确定操作
that.Toast1('你太胖了,此页面即将关闭',()=>{
//点击确定后的操作
});
//TODO 以下写在main.js中
const toast0 = (content) => {
uni.showModal({
content, // 提示的内容,
showCancel: false, // 是否显示取消按钮,
confirmText:'确定', // 确定按钮的文字,默认为取消,最多4个字符(注:多了弹窗不会显示),
confirmColor: '#1E90FF'
})
}
const toast1 = (content,onConfirm) => {
uni.showModal({
content, // 提示的内容,
showCancel: false, // 是否显示取消按钮,
confirmTex:'确定', // 确定按钮的文字,默认为取消,最多4个字符(注:多了弹窗不会显示),
confirmColor: '#1E90FF', // 确定按钮的文字颜色,
success: res => {
if (res.confirm && onConfirm) {
onConfirm()
}
}
})
}
Vue.prototype.Toast0 = toast0
Vue.prototype.Toast1 = toast1
写代码还不如,去非洲送香蕉赚的多