basic.js
import Vue from 'vue'
import store from '@/store'
1、运行环境判断
if(process.env.NODE_ENV == 'development'){
}else{
}
2、请求方法(异步/同步)
const deleteObjNull=(obj)=>{
for(let key in obj){
if(obj[key]==='' || obj[key]===undefined || obj[key]===null || obj[key]=='-' || obj[key]=='NaN'){
delete obj[key];
}
}
}
const uniRequest=(url,data,suc,err)=>{
store.commit('setVariableVal',['loadingText',Vue.prototype.loadText]);
deleteObjNull(data);
uni.request({
url:url,
method: 'POST',
data: data?JSON.stringify(data):'',
success: res => {
if(res.data){
store.commit('setVariableVal',['loadingText','']);
if(res.data.errcode){
uni.showToast({
'title':res.data.errmsg,
'icon':'none'
})
if(err){
err(res);
}
}else{
if(suc){
suc(res);
}
}
}
},
fail:error=>{
store.commit('setVariableVal',['loadingText','']);
}
});
}
const uniRequest2=(url,data,suc)=>{
deleteObjNull(data);
uni.request({
url:url,
method: 'POST',
data: data?JSON.stringify(data):'',
success: res => {
if(res.data){
if(suc){
suc(res);
}
}
}
});
}
const promiseRequest=(url,data)=>{
deleteObjNull(data);
return new Promise((resolve,reject)=>{
uni.request({
url:url,
method: 'POST',
data: data?JSON.stringify(data):''
}).then(resData=>{
let [error,res]=resData;
if(res){
if(res.data.errcode){
uni.showToast({
'title':res.data.errmsg,
'icon':'none'
})
}else{
resolve(res);
}
}
}).catch(err=>{})
})
}
const awaitRequest=async (url,data,noCue)=>{
deleteObjNull(data);
let [error,res]=await uni.request({
url:url,
method: 'POST',
data: data?JSON.stringify(data):''
})
if(res && res.data.errcode && !noCue){
uni.showToast({
'title':res.data.errmsg,
'icon':'none'
})
}else{
return res;
}
}
3、是否可以加载更多数据
const judgeIsLoad=(data,start,size)=>{
let loadingText='';
let isLoad=true;
if(data==''){
if(start>0){
loadingText='没有更多了';
}else{
loadingText='暂无数据';
}
isLoad=false;
}else if(data.length>0 && data.length<size){
loadingText='没有更多了';
isLoad=false;
}else{
loadingText='';
isLoad=true;
}
store.commit('setVariableVal',['loadingText',loadingText]);
return isLoad;
}
4、获取页面路径
const getPagePath=()=>{
let pageArr=getCurrentPages();
let currPage=pageArr[pageArr.length-1];
let pageParam={};
pageParam=currPage.$mp?currPage.$mp.query:{};
pageParam=currPage.options;
let paramStr='';
if(Object.keys(pageParam).length>0){
for(let item in pageParam){
paramStr+=`&${item}=${pageParam[item]}`;
}
paramStr=paramStr.replace('&','');
}
let pagePath=`/${currPage.route}?${paramStr}`;
return pagePath;
}
5、判断登录
const judgeLogin=(forcedLogin=false,relaunch=false)=>{
if(!store.state.userInfo['id']){
uni.getStorage({
key:'userInfo',
success:(res)=>{
store.state.userInfo=JSON.parse(res.data);
},
fail:() => {
if(forcedLogin){
if(relaunch){
uni.reLaunch({
url: '/pages/login'
})
}else{
let pagePath=encodeURIComponent(getPagePath());
uni.redirectTo({
url: '/pages/login?pagePath='+pagePath
})
}
}else{
}
}
})
}
}
6、退出登录
const copyResetState=(type)=>{
if(type){
store.commit('resetState',JSON.parse(Vue.prototype.stateStr));
}else{
Vue.prototype.stateStr=JSON.stringify(store.state);
}
}
const userLoginOut=()=>{
copyResetState(true);
store.commit('setUserInfo',{});
uni.removeStorage({
key:'userInfo'
})
uni.switchTab({
url:'/pages/index'
})
}
7、验证码
const getVerificationCode=(username,codeUrl,obj,countFn)=>{
const rule = [
{name:"username", checkType : "phoneno", checkRule:"11", errorMsg:"请输入正确的手机号码"},
];
let checkRes = graceChecker.check({'username':username}, rule);
if(checkRes){
store.state.securityTimeDec=true;
uniRequest(codeUrl,obj,res=>{
if(countFn){
countFn();
}else{
countDown();
}
})
}else{
uni.showToast({ title: graceChecker.error, icon: "none" });
}
}
const countDown=()=>{
store.state.securityTime=89;
let invalId=setInterval(()=>{
store.state.securityTime--;
if(store.state.securityTime==0 || !store.state.securityTimeDec){
clearInterval(invalId);
store.state.securityTime=90;
}
},1000);
}
8、格式化时间
const fmtDate=(str,d)=>{
let dt=str?new Date(str):new Date();
let year=dt.getFullYear();
let month=fixed2(dt.getMonth()+1);
let date=fixed2(dt.getDate());
let hours=fixed2(dt.getHours());
let minutes=fixed2(dt.getMinutes());
let secounds=fixed2(dt.getSeconds());
let times='';
if(d==1){
times= `${year}-${month}-${date}`;
}else if(d==2){
times= `${month}-${date} ${hours}:${minutes}`;
}else if(d==3){
times= `${year}-${month}-01`;
}else{
times= `${year}-${month}-${date} ${hours}:${minutes}:${secounds}`;
}
return times;
}
const fixed2=(str)=>{
return Number.parseInt(str)<10?'0'+str:str;
}
9、停止当前页面下拉刷新
const stopPullRefresh=()=>{
setTimeout(()=>{
uni.stopPullDownRefresh();
},800)
}
10、图片预览
const previewImg=(arr,current)=>{
uni.previewImage({
urls:arr,
current:current
})
}
11、向上保留两位小数
const ceilFixed2=(num)=>{
let ceilNum=Math.ceil(num*100)/100;
return ceilNum.toFixed(2);
}
12、 store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
userInfo: {},
securityTime:90,
securityTimeDec:true ,
loadingText:''
},
mutations: {
resetState(state,val){
for(let item in state){
state[item]=val[item];
}
},
setVariableVal(state,option){
state[option[0]]=option[1];
}
}
})
export default store