vue-cli init
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import {HttpUtil} from '../../core/utils/http.util'
|
||||
import {LocalStorageUtil} from '../utils/local-storage.util'
|
||||
import globalVariable from "../global-variable";
|
||||
|
||||
export class BaseService {
|
||||
|
||||
httpUtil = HttpUtil
|
||||
|
||||
globalVariable = globalVariable
|
||||
|
||||
localStorageUtil = LocalStorageUtil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
const globalVariable = {
|
||||
|
||||
key: '', // 数据签名key
|
||||
localStoragePrefix: 'localStorage:demo-uview:app:', // todo 不同平台这里需要修改
|
||||
// localStoragePrefix: 'localStorage:wlsh-uview:app:', // todo 不同平台这里需要修改
|
||||
timestamp: new Date().getTime(),
|
||||
|
||||
baseUrl: 'http://xxxxxxxxxxxxxxxxxxxxxxxx:33000/demo-mobile/', // 服务端地址
|
||||
|
||||
systemName: 'uview商城模板',
|
||||
|
||||
runPlatform: "1", // 0-微信小程序版,1-APP版,2-h5版 todo 不同平台这里需要修改
|
||||
|
||||
userInfo: {},
|
||||
|
||||
token: null,
|
||||
|
||||
coordinate: "", // 手机坐标 -- > 113.41189,22.94181
|
||||
|
||||
orderSequenceNumber: null, // 餐饮号
|
||||
|
||||
tempData: {}, // 存放临时数据,例如跳转页面时获取前一个页面保存的数据。
|
||||
};
|
||||
|
||||
export default globalVariable
|
||||
@@ -0,0 +1,81 @@
|
||||
import {LocalStorageUtil} from "../utils/local-storage.util";
|
||||
import globalVariable from "../global-variable";
|
||||
import {CommonUtil} from "../utils/common.util";
|
||||
import {AuthUtil} from "../utils/auth.util";
|
||||
|
||||
// 这里的vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token
|
||||
// 同时,我们也可以在此使用getApp().globalData,如果你把token放在getApp().globalData的话,也是可以使用的
|
||||
const install = (Vue, vm) => {
|
||||
Vue.prototype.$u.http.setConfig({
|
||||
// baseUrl: 'https://api.youzixy.com',
|
||||
// 如果将此值设置为true,拦截回调中将会返回服务端返回的所有数据response,而不是response.data
|
||||
// 设置为true后,就需要在this.$u.http.interceptor.response进行多一次的判断,请打印查看具体值
|
||||
originalData: true,
|
||||
// 设置自定义头部content-type
|
||||
// header: {
|
||||
// 'content-type': 'xxx'
|
||||
// }
|
||||
});
|
||||
// 请求拦截,配置Token等参数
|
||||
Vue.prototype.$u.http.interceptor.request = (config) => {
|
||||
// 添加token信息
|
||||
config.header.Authorization = globalVariable.token;
|
||||
config.header.timestamp = new Date().getTime();
|
||||
config.header.sign = CommonUtil.generateSign(config.header.timestamp);
|
||||
|
||||
// 方式一,存放在vuex的token,假设使用了uView封装的vuex方式,见:https://uviewui.com/components/globalVariable.html
|
||||
// config.header.token = vm.token;
|
||||
|
||||
// 方式二,如果没有使用uView封装的vuex方法,那么需要使用$store.state获取
|
||||
// config.header.token = vm.$store.state.token;
|
||||
|
||||
// 方式三,如果token放在了globalData,通过getApp().globalData获取
|
||||
// config.header.token = getApp().globalData.username;
|
||||
|
||||
// 方式四,如果token放在了Storage本地存储中,拦截是每次请求都执行的,所以哪怕您重新登录修改了Storage,下一次的请求将会是最新值
|
||||
// const token = uni.getStorageSync('token');
|
||||
// config.header.token = token;
|
||||
return config;
|
||||
}
|
||||
// 响应拦截,判断状态码是否通过
|
||||
Vue.prototype.$u.http.interceptor.response = (res) => {
|
||||
console.log("Vue.prototype.$u.http.interceptor.response", res)
|
||||
|
||||
if (res.header.Authorization) {
|
||||
console.log('------------新的token-----------', res.header.Authorization)
|
||||
globalVariable.token = res.header.Authorization
|
||||
LocalStorageUtil.setItem('token', globalVariable.token)
|
||||
}
|
||||
|
||||
// 如果把originalData设置为了true,这里得到将会是服务器返回的所有的原始数据
|
||||
// 判断可能变成了res.statusCode,或者res.data.code之类的,请打印查看结果
|
||||
if (res.statusCode == 200) {
|
||||
// // 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
|
||||
// 如果把originalData设置为了true,这里return回什么,this.$u.post的then回调中就会得到什么
|
||||
return res.data;
|
||||
} else {
|
||||
if (res.statusCode == 401) {
|
||||
AuthUtil.logout();
|
||||
} else {
|
||||
let message = "系统异常";
|
||||
if (res.data.msg) {
|
||||
message = res.data.msg;
|
||||
}
|
||||
if (res.data.message) {
|
||||
message = res.data.message;
|
||||
}
|
||||
CommonUtil.alert(message)
|
||||
}
|
||||
|
||||
uni.hideLoading();
|
||||
|
||||
// 如果返回false,则会调用Promise的reject回调,
|
||||
// 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
install
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import globalVariable from "../global-variable";
|
||||
import {PaginationModel} from "../model/pagination.model";
|
||||
import {CommonUtil} from "../utils/common.util";
|
||||
import {UFormUtil} from "../utils/u-form.util";
|
||||
import {LocalStorageUtil} from "../utils/local-storage.util";
|
||||
import {TabbarUtil} from "../utils/tabbar.util";
|
||||
|
||||
/**
|
||||
* mixin的作用是多个组件可以共享数据和方法,在使用mixin的组件中引入后,mixin中的方法和属性也就并入到该组件中,
|
||||
* 可以直接使用,在已有的组件数据和方法进行了扩充。引入mixin分全局引用和局部引用。
|
||||
* todo 可以代替基类base的功能
|
||||
*
|
||||
* todo Page页面生命周期函数执行顺序
|
||||
* beforeCreate => onLoad => onShow => created => beforeMount => onReady => mounted
|
||||
* 刷新数据后
|
||||
* beforeUpdate => updated
|
||||
*
|
||||
* vue 父子组件的生命周期顺序加载渲染过程
|
||||
* 父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted
|
||||
*
|
||||
* 子组件更新过程
|
||||
* 父beforeUpdate->子beforeUpdate->子updated->父updated
|
||||
*
|
||||
* 父组件更新过程
|
||||
* 父beforeUpdate->父updated
|
||||
*
|
||||
* 销毁过程
|
||||
* 父beforeDestroy->子beforeDestroy->子destroyed->父destroyed
|
||||
*/
|
||||
const myMixin = {
|
||||
data() {
|
||||
return {
|
||||
// _self: null, // todo 不能直接赋值否则u-view框架报错, 当vue作为组件<componentName></componentName>引用时,组件模板页面<template/>中的this为null,这时需要使用_self变量代替。
|
||||
uni: uni, // 不这样设置,template页面中不能直接使用(例如:@click="uni.navigateTo({url: 'xxx})")
|
||||
$u: this.$u, // 不这样设置,template页面中取不到值
|
||||
CommonUtil: CommonUtil, // 不这样设置,template页面中无法直接使用
|
||||
TabbarUtil: TabbarUtil, // 不这样设置,template页面中无法直接使用
|
||||
UFormUtil: UFormUtil, // 不这样设置,template页面中无法直接使用
|
||||
globalVariable: globalVariable, // todo <template/>模板页面中可以直接使用,js中可以直接使用
|
||||
pagination: new PaginationModel(), // 每个组件都是一个新的对象互不影响
|
||||
urlParams: {}, // 导航过来的url参数?a=1&b=2 ==> {a: 1, b: 2} <template/>可以直接获取
|
||||
objParams: {}, // 导航过来的对象参数 todo 导航过来的是同一个对象,改变内容所有引用的页面将会同时受到影响。 <template/>可以直接获取
|
||||
currentRouteUrl: '',
|
||||
// 时间控件显示格式:2020-09-22 16:57:38
|
||||
pickerFormatDatetime: {
|
||||
year: true,
|
||||
month: true,
|
||||
day: true,
|
||||
hour: true,
|
||||
minute: true,
|
||||
second: true,
|
||||
},
|
||||
// 时间控件显示格式:2020-09-22
|
||||
pickerFormatDate: {
|
||||
year: true,
|
||||
month: true,
|
||||
day: true,
|
||||
hour: false,
|
||||
minute: false,
|
||||
second: false,
|
||||
}
|
||||
}
|
||||
},
|
||||
// options 参数为null,当组件使用时不会被调用
|
||||
beforeCreate(options) {
|
||||
// console.log(`myMixin--------------------------------beforeCreate(${JSON.stringify(options)})--------------------------------`)
|
||||
const _self = this;
|
||||
// 刷新页面时重新赋值,否则页面会报错。
|
||||
if (!globalVariable.token) {
|
||||
let token = LocalStorageUtil.getItem("token");
|
||||
let userInfo = LocalStorageUtil.getItem("userInfo");
|
||||
globalVariable.orderSequenceNumber = null; // 删除已扫码的餐饮号
|
||||
if (token && userInfo) {
|
||||
globalVariable.token = token;
|
||||
globalVariable.userInfo = userInfo;
|
||||
}
|
||||
}
|
||||
},
|
||||
// options页面导航的参数,当组件使用时不会被调用
|
||||
onLoad(options) {
|
||||
console.log(`myMixin--------------------------------onLoad(options)--------------------------------`, options);
|
||||
const _self = this;
|
||||
_self.urlParams = options; // app端没有this.$root.$mp.query参数。
|
||||
if (!_self.urlParams) {
|
||||
_self.urlParams = {};
|
||||
}
|
||||
console.log("urlParams------------------------", _self.urlParams);
|
||||
|
||||
if (_self.urlParams && _self.urlParams.q && _self.urlParams.scancode_time) {
|
||||
_self.urlParams.url = decodeURIComponent(_self.urlParams.q);
|
||||
_self.urlParams = CommonUtil.getUrlParams(_self.urlParams.url);
|
||||
_self.urlParams.isScan = "1"; // 是否扫码进入到该页面
|
||||
console.log("微信扫码进入小程序结果urlParams------------------------", _self.urlParams);
|
||||
}
|
||||
|
||||
// 兼容部分手机机型不能从导航事件中获取objParams问题。
|
||||
if (!globalVariable.objParams) {
|
||||
globalVariable.objParams = {};
|
||||
}
|
||||
_self.objParams = globalVariable.objParams;
|
||||
console.log("globalVariable.objParams------------------------", _self.objParams);
|
||||
|
||||
const eventChannel = this.getOpenerEventChannel();
|
||||
eventChannel.on('objParams', function (data) {
|
||||
_self.objParams = data;
|
||||
console.log("objParams------------------------", data);
|
||||
});
|
||||
|
||||
if (this.validateForm) {
|
||||
UFormUtil.init(this.validateForm);
|
||||
console.log("validateForm表单对象初始化成功--------------------------------", this.validateForm);
|
||||
}
|
||||
},
|
||||
// options 参数为null,当组件使用时不会被调用
|
||||
onShow(options) {
|
||||
// console.log(`myMixin--------------------------------onShow(${JSON.stringify(options)})--------------------------------`)
|
||||
},
|
||||
// options 参数为null,当组件使用时不会被调用
|
||||
created(options) {
|
||||
// console.log(`myMixin--------------------------------created(${JSON.stringify(options)})--------------------------------`)
|
||||
},
|
||||
// options 参数为null,当组件使用时不会被调用
|
||||
onReady(options) {
|
||||
// console.log(`myMixin--------------------------------onReady(${JSON.stringify(options)})--------------------------------`)
|
||||
if (this.validateForm && !this.validateForm.controls) { // todo 当组件使用时onLoad方法不会被调用,所以需要在这里初始化。
|
||||
UFormUtil.init(this.validateForm);
|
||||
console.log("validateForm表单对象初始化成功--------------------------------", this.validateForm);
|
||||
}
|
||||
if (this.validateForm && this.validateForm.rules && this.$refs.validateFormRef) {
|
||||
this.$refs.validateFormRef.setRules(this.validateForm.rules);
|
||||
console.log("validateFormRef表单校验规则初始化成功--------------------------------", this.validateForm);
|
||||
}
|
||||
},
|
||||
// options 参数为null,todo 当组件使用时会被调用
|
||||
mounted(options) {
|
||||
// console.log(`myMixin--------------------------------mounted(${JSON.stringify(options)})--------------------------------`)
|
||||
this._self = this; // todo 当vue作为组件<componentName></componentName>引用时,组件模板页面<template/>中的this为null,这时需要使用_self变量代替。
|
||||
|
||||
if (this.validateForm && !this.validateForm.controls) { // todo 当组件使用时onLoad方法不会被调用,所以需要在这里初始化。
|
||||
UFormUtil.init(this.validateForm);
|
||||
console.log("validateForm表单对象初始化成功--------------------------------", this.validateForm);
|
||||
}
|
||||
|
||||
if (this.validateForm && this.validateForm.rules && this.$refs.validateFormRef) {
|
||||
this.$refs.validateFormRef.setRules(this.validateForm.rules);
|
||||
console.log("validateFormRef表单校验规则初始化成功--------------------------------", this.validateForm);
|
||||
}
|
||||
|
||||
// 获取路由数组
|
||||
let routes = getCurrentPages();
|
||||
if (routes && routes.length) {
|
||||
this.currentRouteUrl = routes[routes.length - 1].route;
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
/**
|
||||
* template页面中使用这种方式才能跳转页面
|
||||
* @param url
|
||||
* @param urlParams
|
||||
* @param objParams 传递对象类型数据给下一个页面,改变内容所有引用的页面将会同时受到影响。
|
||||
* 导航:navigateTo(url, urlParams, objParams),跳转页面的objParams将指向同一个地址,修改将同时受到影响。
|
||||
* 导航:navigateTo(url, urlParams, {objParams: objParams}) 跳转页面的objParams对象是一个全新的对象,指向不同的地址。对其修改不影响原对象的值。
|
||||
* todo 在<template/>中使用{tbOrder: tbOrder}的方式传值时,将产生一个全新的tbOrder副本,并不是只向原来的tbOrder地址,所以对新的tbOrder修改不会影响原来的tbOrder。
|
||||
* todo 在<template/>中使用globalVariable.tempData.tbOrder = tbOrder赋值后globalVariable.tempData.tbOrder不是tbOrder,而是一个全新属性错乱的对象。
|
||||
*
|
||||
* 所以要传递多个对象并且每个对象始终保持是同一个地址,则需要在js中实现。
|
||||
* 例如:@click="test(url, urlParams, obj1, obj2)"
|
||||
* test(url, urlParams, obj1, obj2){
|
||||
* this.navigateTo(url, urlParams, {obj1, obj2});
|
||||
* // 或者
|
||||
* this.navigateTo(url, urlParams).then(res=>{
|
||||
* res.eventChannel.emit('objParams', {obj1, obj2});
|
||||
* })
|
||||
* }
|
||||
*/
|
||||
navigateTo(url, urlParams, objParams) {
|
||||
|
||||
// 兼容部分手机机型不能从导航事件中获取objParams问题。
|
||||
globalVariable.objParams = objParams;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (urlParams) {
|
||||
if (url.indexOf("?") === -1) {
|
||||
url = url + "?" + CommonUtil.objectToUrlParams(urlParams);
|
||||
} else {
|
||||
url = url + "&" + CommonUtil.objectToUrlParams(urlParams);
|
||||
}
|
||||
}
|
||||
uni.navigateTo({
|
||||
url: url,
|
||||
success: function (res) {
|
||||
if (objParams) {
|
||||
// 通过eventChannel向被打开页面传送数据
|
||||
res.eventChannel.emit('objParams', objParams)
|
||||
}
|
||||
resolve(res);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
/**
|
||||
* 刷新数据
|
||||
* @param dataList
|
||||
*/
|
||||
doRefresh(dataList) {
|
||||
// 清空数据。
|
||||
// console.log("myMixin--------------------------------doRefresh()--------------------------------")
|
||||
dataList.splice(0, dataList.length);
|
||||
this.pagination = new PaginationModel();
|
||||
this.$forceUpdate();
|
||||
this.$nextTick(() => {
|
||||
this.pagination = new PaginationModel();
|
||||
this.doInfinite();
|
||||
});
|
||||
},
|
||||
/**
|
||||
* 根据componentRef切换底部菜单栏选项
|
||||
* @param componentRef
|
||||
*/
|
||||
switchTarBarByComponentRef(componentRef) {
|
||||
const _self = this;
|
||||
let pages = getCurrentPages();
|
||||
console.log(pages);
|
||||
pages.forEach((page, index) => {
|
||||
if (page.route === 'pages/sub/sub1-tabs/tabs/index') {
|
||||
// h5调用属性和方法可以不用page.$vm,但是微信小程序必须是page.$vm.否则报错。
|
||||
page.$vm.tarbar.forEach((item, index) => {
|
||||
if (item.componentRef === componentRef) {
|
||||
page.$vm.onChangeTabbarTab(index);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default myMixin
|
||||
@@ -0,0 +1,96 @@
|
||||
export class PaginationModel {
|
||||
/**
|
||||
* 页码,从1开始
|
||||
*/
|
||||
pageNum = 1;
|
||||
/**
|
||||
* 页面大小
|
||||
*/
|
||||
pageSize = 10;
|
||||
|
||||
size = 0;
|
||||
|
||||
orderBy = null;
|
||||
|
||||
/**
|
||||
* 起始行
|
||||
*/
|
||||
startRow = 1;
|
||||
/**
|
||||
*
|
||||
* 末行
|
||||
*/
|
||||
endRow = 0;
|
||||
/**
|
||||
* 总数
|
||||
*/
|
||||
total = 0;
|
||||
/**
|
||||
* 总页数
|
||||
*/
|
||||
pages = 0;
|
||||
|
||||
data = [];
|
||||
|
||||
firstPage = 1;
|
||||
|
||||
prePage = 0;
|
||||
|
||||
nextPage = 0;
|
||||
|
||||
lastPage = 1;
|
||||
|
||||
isFirstPage = true;
|
||||
|
||||
/**
|
||||
* 是否是最后一页
|
||||
*/
|
||||
isLastPage = false;
|
||||
|
||||
hasPreviousPage = false
|
||||
|
||||
/**
|
||||
* 是否有下一页
|
||||
*/
|
||||
hasNextPage = false;
|
||||
|
||||
navigatePages = 8;
|
||||
|
||||
navigatepageNums = [1];
|
||||
|
||||
isLast = false;
|
||||
|
||||
// <!--通过status设置组件的状态,加载前值为loadmore,加载中为loading,没有数据为nomore-->
|
||||
status = 'nomore';
|
||||
|
||||
refreshPage(data) {
|
||||
for (let attr in data) {
|
||||
this[attr] = data[attr]
|
||||
}
|
||||
if (this.hasNextPage) {
|
||||
this.pageNum = this.pageNum + 1
|
||||
this.status = 'loadmore'
|
||||
} else {
|
||||
this.status = 'nomore'
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页
|
||||
* pagination[page]
|
||||
* pagination[perpage]
|
||||
* 排序
|
||||
* sort[field]
|
||||
* sort[sort]
|
||||
*/
|
||||
appendToUrl(pageNum, pageSize) {
|
||||
if (pageNum) {
|
||||
this.pageNum = pageNum;
|
||||
}
|
||||
if (pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
return `pageNum=${this.pageNum}&pageSize=${this.pageSize}`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import globalVariable from "../global-variable";
|
||||
import {LocalStorageUtil} from "./local-storage.util";
|
||||
import {CommonUtil} from "./common.util";
|
||||
|
||||
export class AuthUtil {
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
static logout(message = "会话已过期,请重新登录") {
|
||||
globalVariable.token = null;
|
||||
globalVariable.userInfo = {};
|
||||
globalVariable.orderSequenceNumber = null;
|
||||
globalVariable.coordinate = null;
|
||||
LocalStorageUtil.removeItem("token");
|
||||
LocalStorageUtil.removeItem("userInfo");
|
||||
CommonUtil.toastReLaunch(message, "/pages/main/login/index");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export class BaiduMapUtil {
|
||||
|
||||
/**
|
||||
* WGS84转GCj02
|
||||
* 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
|
||||
* @param lng
|
||||
* @param lat
|
||||
* @returns {*[]}
|
||||
*/
|
||||
static wgs84togcj02tobd09(lng, lat) {
|
||||
const xPI = 3.14159265358979324 * 3000.0 / 180.0
|
||||
const PI = 3.1415926535897932384626
|
||||
const a = 6378245.0
|
||||
const ee = 0.00669342162296594323
|
||||
// WGS84转GCj02
|
||||
let dlat = this.transformlat(lng - 105.0, lat - 35.0)
|
||||
let dlng = this.transformlng(lng - 105.0, lat - 35.0)
|
||||
let radlat = lat / 180.0 * PI
|
||||
let magic = Math.sin(radlat)
|
||||
magic = 1 - ee * magic * magic
|
||||
let sqrtmagic = Math.sqrt(magic)
|
||||
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI)
|
||||
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI)
|
||||
let mglat = lat + dlat
|
||||
let mglng = lng + dlng
|
||||
// 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
|
||||
let z = Math.sqrt(mglng * mglng + mglat * mglat) + 0.00002 * Math.sin(mglat * xPI)
|
||||
let theta = Math.atan2(mglat, mglng) + 0.000003 * Math.cos(mglng * xPI)
|
||||
let bdlng = z * Math.cos(theta) + 0.0065
|
||||
let bdlat = z * Math.sin(theta) + 0.006
|
||||
// return [bdlng, bdlat]
|
||||
return {lng: bdlng, lat: bdlat}
|
||||
}
|
||||
|
||||
static transformlat(lng, lat) {
|
||||
const PI = 3.1415926535897932384626
|
||||
let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng))
|
||||
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
|
||||
ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0
|
||||
ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0
|
||||
return ret
|
||||
}
|
||||
|
||||
static transformlng(lng, lat) {
|
||||
const PI = 3.1415926535897932384626
|
||||
let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
|
||||
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
|
||||
ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0
|
||||
ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0
|
||||
return ret
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,830 @@
|
||||
import Vue from 'vue'
|
||||
import md5Libs from "uview-ui/libs/function/md5";
|
||||
import globalVariable from "../global-variable";
|
||||
|
||||
export class CommonUtil {
|
||||
|
||||
// ----------------------------------------------原生js----------------------------------------------
|
||||
|
||||
/**
|
||||
* 生成签名
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
static generateSign(timestamp) {
|
||||
return md5Libs.md5(md5Libs.md5(timestamp + globalVariable.key) + timestamp + globalVariable.key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 随机生成uuid
|
||||
* @returns {string}
|
||||
*/
|
||||
static generateUUID() {
|
||||
var s = []
|
||||
var hexDigits = '0123456789abcdef'
|
||||
for (var i = 0; i < 36; i++) {
|
||||
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
|
||||
}
|
||||
s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
|
||||
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
|
||||
s[8] = s[13] = s[18] = s[23] = '-'
|
||||
|
||||
var uuid = s.join('')
|
||||
return uuid
|
||||
}
|
||||
|
||||
/**
|
||||
* 随机生成uuid
|
||||
*/
|
||||
static randomUUID() {
|
||||
return this.generateUUID();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成范围随机数
|
||||
* @param max
|
||||
* @param min
|
||||
* @returns {number}
|
||||
*/
|
||||
static random(max, min) {
|
||||
return Math.round(Math.random() * (max - min) + min);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成code编号
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
static generateCode() {
|
||||
let identifyingCode = parseInt((Math.random() * 9 + 1) * 100000 + '');
|
||||
return this.dateFormat(new Date(), 'yyyyMMddHHmmss') + identifyingCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取手机端的屏幕宽度
|
||||
*/
|
||||
static getScreenWidth() {
|
||||
// 小程序会报错
|
||||
// let width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
|
||||
let width = uni.getSystemInfoSync().screenWidth;
|
||||
console.log(width);
|
||||
return width;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取手机端的屏幕高度
|
||||
*/
|
||||
static getScreenHeight() {
|
||||
// 微信小程序会报错
|
||||
// let height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
|
||||
let height = uni.getSystemInfoSync().screenHeight;
|
||||
console.log(height);
|
||||
return height;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成包含数字、大写字母、小写字母的随机数
|
||||
* @param length
|
||||
* @returns {string}
|
||||
*/
|
||||
static randomStr(length = 4) { //封装,以便日后使用。
|
||||
//创建一个空字符,用于存放随机数/字母
|
||||
var strData = "";
|
||||
//生成随机字符库 (验证码四位,随机数三种,取公倍数12,所以循环4次。也可以是120次,1200次。)
|
||||
for (var i = 0; i < length; i++) {
|
||||
var num = this.random(0, 9);//生成0-9的随机数
|
||||
var az = String.fromCharCode(this.random(97, 122));//生成a-z
|
||||
var AZ = String.fromCharCode(this.random(65, 90));//生成A-Z
|
||||
|
||||
strData = strData + num + az + AZ;//将生成的字符进行字符串拼接
|
||||
}
|
||||
// 开始真正的随机(从随机字符库中随机取出四个)
|
||||
var str = "";
|
||||
for (var i = 0; i < 4; i++) {
|
||||
str += strData[this.random(0, strData.length - 1)]
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并对象值
|
||||
*/
|
||||
static mergeData(_self, target, ...sources) {
|
||||
for (let index in sources) {
|
||||
let source = sources[index]
|
||||
for (let attrName in source) {
|
||||
_self.$set(target, attrName, source[attrName])
|
||||
if (typeof source[attrName] === 'object') {
|
||||
this.mergeData(_self, target[attrName], source[attrName])
|
||||
}
|
||||
}
|
||||
}
|
||||
_self.$forceUpdate();
|
||||
return target
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除左右两端的空格
|
||||
* @param str
|
||||
* @returns {*}
|
||||
*/
|
||||
static trim(str) {
|
||||
let result = str
|
||||
try {
|
||||
result = str.replace(/(^\s*)|(\s*$)/g, '')
|
||||
} catch (e) {
|
||||
// 非字符串没有.replace方法
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 对象转url参数
|
||||
* @param obj
|
||||
* @param isEncodeURI
|
||||
* @returns {string}
|
||||
*/
|
||||
static objectToUrlParams(obj, isEncodeURI) {
|
||||
// 优化参数
|
||||
for (let attrName in obj) {
|
||||
if (obj[attrName] === undefined || obj[attrName] == null || obj[attrName] === 'undefined' || obj[attrName] === 'null' || CommonUtil.trim(obj[attrName]) === '') {
|
||||
delete obj[attrName]
|
||||
}
|
||||
}
|
||||
if (!isEncodeURI) { // 是否编码参数
|
||||
return Object.keys(obj).map(function (key) {
|
||||
return ''.concat(key, '=').concat(obj[key])
|
||||
}).join('&')
|
||||
} else {
|
||||
return Object.keys(obj).map(function (key) {
|
||||
return ''.concat(encodeURIComponent(key), '=').concat(encodeURIComponent(obj[key]))
|
||||
}).join('&')
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 时间字符串转时间戳 2020-09-27 17:06:21 --> 1601197581000
|
||||
* @param datetimeStr
|
||||
*/
|
||||
static datetimeStrToTimestamp(datetimeStr) {
|
||||
datetimeStr = datetimeStr.substring(0, 19);
|
||||
datetimeStr = datetimeStr.replace(/-/g, '/'); //必须把日期'-'转为'/'
|
||||
let timestamp = new Date(datetimeStr).getTime();
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期
|
||||
* @param date
|
||||
* @param fmt yyyy-MM-dd HH:mm:ss
|
||||
* @returns {*}
|
||||
*/
|
||||
static dateFormat(date, fmt = 'yyyy-MM-dd HH:mm:ss') {
|
||||
// 如果是日期字符串,则转成日志类型
|
||||
if (typeof date === 'string') {
|
||||
date = new Date(date);
|
||||
}
|
||||
|
||||
let ret;
|
||||
const opt = {
|
||||
"y+": date.getFullYear().toString(), // 年
|
||||
"M+": (date.getMonth() + 1).toString(), // 月
|
||||
"d+": date.getDate().toString(), // 日
|
||||
"H+": date.getHours().toString(), // 时
|
||||
"m+": date.getMinutes().toString(), // 分
|
||||
"s+": date.getSeconds().toString() // 秒
|
||||
// 有其他格式化字符需求可以继续添加,必须转化成字符串
|
||||
};
|
||||
for (let k in opt) {
|
||||
ret = new RegExp("(" + k + ")").exec(fmt);
|
||||
if (ret) {
|
||||
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
|
||||
}
|
||||
}
|
||||
return fmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个时间相差的天数
|
||||
* @param date1
|
||||
* @param date2
|
||||
* @returns {number}
|
||||
*/
|
||||
static getDiffDays(date1, date2) {
|
||||
if (typeof date1 === 'string') {
|
||||
date1 = new Date(date1);
|
||||
}
|
||||
if (typeof date2 === 'string') {
|
||||
date2 = new Date(date2);
|
||||
}
|
||||
/*获取之间的天数*/
|
||||
let diffDays = (date2.getTime() - date1.getTime()) / (3600 * 24 * 1000);
|
||||
return parseInt(diffDays);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除对象中所有的null、undefined属性值
|
||||
*/
|
||||
static deleteNullAttrInObject(obj, removeEmptyStr = true) {
|
||||
for (var key in obj) {
|
||||
if (obj[key] === null) {
|
||||
delete obj[key]
|
||||
}
|
||||
if (obj[key] === undefined) {
|
||||
delete obj[key]
|
||||
}
|
||||
if (removeEmptyStr && obj[key] === '') {
|
||||
delete obj[key]
|
||||
}
|
||||
if (Array.isArray(obj[key]) && obj[key].length === 0) { // 删除空数组[]属性
|
||||
delete obj[key]
|
||||
}
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
static urlParamsAppendToUrl(url, urlParams) {
|
||||
if (urlParams) {
|
||||
if (url.indexOf("?") === -1) {
|
||||
url = url + "?" + this.objectToUrlParams(urlParams);
|
||||
} else {
|
||||
url = url + "&" + this.objectToUrlParams(urlParams);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 毫秒转换友好的显示格式
|
||||
* 输出格式:21小时前
|
||||
* @param {[type]} time [description]
|
||||
* @return {[type]} [description]
|
||||
*/
|
||||
static showTime(datetime) {
|
||||
|
||||
//获取js 时间戳
|
||||
var time = new Date().getTime();
|
||||
|
||||
//去掉 js 时间戳后三位,与php 时间戳保持一致
|
||||
time = parseInt((time - this.datetimeStrToTimestamp(datetime)) / 1000 + '');
|
||||
|
||||
//存储转换值
|
||||
var s;
|
||||
if (time == 0) {
|
||||
return '刚刚';
|
||||
} else if (time < 60) {
|
||||
return time + '秒前';
|
||||
} else if ((time < 60 * 60) && (time >= 60)) {
|
||||
//超过十分钟少于1小时
|
||||
s = Math.floor(time / 60);
|
||||
return s + '分钟前';
|
||||
} else if ((time < 60 * 60 * 24) && (time >= 60 * 60)) {
|
||||
//超过1小时少于24小时
|
||||
s = Math.floor(time / 60 / 60);
|
||||
return s + '小时前';
|
||||
} else if ((time < 60 * 60 * 24 * 30) && (time >= 60 * 60 * 24)) {
|
||||
//超过1天少于30天内
|
||||
s = Math.floor(time / 60 / 60 / 24);
|
||||
return s + '天前';
|
||||
} else {
|
||||
//超过3天
|
||||
// var date = new Date(parseInt(datetime) * 1000);
|
||||
// return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
|
||||
return this.dateFormat(datetime, 'MM-dd HH:mm');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字符串编码成base64
|
||||
* @param str
|
||||
* @returns {string}
|
||||
*/
|
||||
static toBase64Encode(str) {
|
||||
var c1, c2, c3;
|
||||
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var i = 0, len = str.length, string = '';
|
||||
|
||||
while (i < len) {
|
||||
c1 = str.charCodeAt(i++) & 0xff;
|
||||
if (i == len) {
|
||||
string += base64EncodeChars.charAt(c1 >> 2);
|
||||
string += base64EncodeChars.charAt((c1 & 0x3) << 4);
|
||||
string += "==";
|
||||
break;
|
||||
}
|
||||
c2 = str.charCodeAt(i++);
|
||||
if (i == len) {
|
||||
string += base64EncodeChars.charAt(c1 >> 2);
|
||||
string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
|
||||
string += base64EncodeChars.charAt((c2 & 0xF) << 2);
|
||||
string += "=";
|
||||
break;
|
||||
}
|
||||
c3 = str.charCodeAt(i++);
|
||||
string += base64EncodeChars.charAt(c1 >> 2);
|
||||
string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
|
||||
string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
|
||||
string += base64EncodeChars.charAt(c3 & 0x3F)
|
||||
}
|
||||
return string
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加属性别名
|
||||
* @param object
|
||||
* @param alias
|
||||
* {
|
||||
* "name": "label", 给name属性取个别名label
|
||||
* "code": "value" 给code属性取个别名value
|
||||
* }
|
||||
*/
|
||||
static objectAlias(object, alias = {'name': 'label', 'code': 'value'}) {
|
||||
if (!object) {
|
||||
return;
|
||||
}
|
||||
// 数组
|
||||
if (Array.isArray(object)) {
|
||||
object.forEach(item => {
|
||||
for (let attrName in alias) {
|
||||
// 将一个属性取一个别名
|
||||
if (attrName.indexOf(",") === -1) {
|
||||
item[alias[attrName]] = item[attrName];
|
||||
} else {// 将多个属性取同一个别名,每个属性名/值以逗号隔开
|
||||
let attrNames = attrName.split(",");
|
||||
let value = [];
|
||||
for (let i = 0; i < attrNames.length; i++) {
|
||||
value.push(item[attrNames[i]]);
|
||||
}
|
||||
item[alias[attrName]] = value.join(",");
|
||||
}
|
||||
}
|
||||
|
||||
if (item.children) {
|
||||
this.objectAlias(item.children, alias);
|
||||
}
|
||||
});
|
||||
} else { // 对象
|
||||
for (let attrName in alias) {
|
||||
if (attrName.indexOf(",") === -1) {
|
||||
object[alias[attrName]] = object[attrName];
|
||||
} else {
|
||||
let attrNames = attrName.split(",");
|
||||
let value = [];
|
||||
for (let i = 0; i < attrNames.length; i++) {
|
||||
value.push(item[attrNames[i]]);
|
||||
}
|
||||
item[alias[attrName]] = value.join(",");
|
||||
}
|
||||
}
|
||||
if (object.children) {
|
||||
this.objectAlias(object.children, alias);
|
||||
}
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新对象值
|
||||
* @param _selfVue
|
||||
* @param obj
|
||||
*/
|
||||
static refreshObj(_selfVue, obj) {
|
||||
const _self = this;
|
||||
for (let key in obj) {
|
||||
//排除掉原型继承而来的属性
|
||||
if (!obj.hasOwnProperty(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(key, obj[key]);
|
||||
if (typeof obj[key] === 'object' || typeof obj[key] === 'function') {
|
||||
_self.refreshObj(_selfVue, obj[key]);
|
||||
} else if (Array.isArray(obj[key])) {
|
||||
obj[key].forEach((item) => {
|
||||
_self.refreshObj(_selfVue, item);
|
||||
})
|
||||
} else {
|
||||
_selfVue.$set(obj, key, obj[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否是JSON字符串
|
||||
* @param str
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static isJSON(str) {
|
||||
if (typeof str == 'string') {
|
||||
try {
|
||||
var obj = JSON.parse(str);
|
||||
if (typeof obj == 'object' && obj) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('error:' + str + '!!!' + e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否是数字
|
||||
* @param checkVal
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static isNumber(checkVal) {
|
||||
var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
|
||||
return reg.test(checkVal);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取url中的参数
|
||||
*/
|
||||
static getUrlParams(url) {
|
||||
// url不存在参数
|
||||
if (url.indexOf("?") === -1) {
|
||||
return {};
|
||||
}
|
||||
// http://www.baidu.com/test?a=1&b=2
|
||||
let params = url.split("?")[1]; // a=1&b=2
|
||||
params = params.split("&"); // ['a=1', 'b=2']
|
||||
let urlParams = {};
|
||||
params.forEach(item => {
|
||||
let keyValue = item.split("="); // 'a=1' --> ['a', '1']
|
||||
urlParams[keyValue[0]] = keyValue[1];
|
||||
});
|
||||
return urlParams; // {a: 1, b: 2}
|
||||
}
|
||||
|
||||
// ----------------------------------------------uview-ui----------------------------------------------
|
||||
|
||||
/**
|
||||
* 深度克隆
|
||||
* 当我们将一个对象(变量A)赋值给另一个变量(变量B)时,修改变量B,因为对象引用的特性,导致A也同时被修改,
|
||||
* 所以有时候我们需要将A克隆给B,这样修改B的时候,就不会 导致A也被修改。
|
||||
* @param object
|
||||
* @returns {*}
|
||||
*/
|
||||
static deepClone(object = {}) {
|
||||
return Vue.prototype.$u.deepClone(object)
|
||||
}
|
||||
|
||||
/**
|
||||
* 对象深度合并
|
||||
* 在ES6中,我们可以很方便的使用Object.assign进行对象合并,但这只是浅层的合并,如果对象的属性为数组或者对象的时候,会导致属性内部的值丢失。
|
||||
* 注意: 此处合并不同于Object.assign,因为Object.assign(a, b)会修改a的值为最终的结果(这往往不是我们所期望的),但是deepMerge(a, b)并不会修改a的值。
|
||||
* @param target
|
||||
* @param source
|
||||
* @returns {boolean|*}
|
||||
*/
|
||||
static deepMerge(target = {}, source = {}) {
|
||||
return Vue.prototype.$u.deepMerge(target, source)
|
||||
}
|
||||
|
||||
/**
|
||||
* md5加密
|
||||
* @param value
|
||||
* console.log(md5Libs.md5('uView')) // 结果为:55c859b4750225eb1cdbd9e0403ee274
|
||||
*/
|
||||
static md5(value) {
|
||||
return md5Libs.md5(value)
|
||||
}
|
||||
|
||||
|
||||
// ----------------------------------------------uni-app原生api----------------------------------------------
|
||||
static navigateTo(url, urlParams, objParams) {
|
||||
|
||||
// 兼容部分手机机型不能从导航事件中获取objParams问题。
|
||||
globalVariable.objParams = objParams;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (urlParams) {
|
||||
if (url.indexOf("?") === -1) {
|
||||
url = url + "?" + CommonUtil.objectToUrlParams(urlParams);
|
||||
} else {
|
||||
url = url + "&" + CommonUtil.objectToUrlParams(urlParams);
|
||||
}
|
||||
}
|
||||
uni.navigateTo({
|
||||
url: url,
|
||||
success: function (res) {
|
||||
if (objParams) {
|
||||
// 通过eventChannel向被打开页面传送数据
|
||||
res.eventChannel.emit('objParams', objParams)
|
||||
}
|
||||
resolve(res);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param title
|
||||
* @param duration
|
||||
* @param icon
|
||||
success、warn、error 显示成功图标,此时 title 文本最多显示 7 个汉字长度。默认值
|
||||
loading 显示加载图标,此时 title 文本最多显示 7 个汉字长度。 支付宝小程序不支持
|
||||
none 不显示图标,此时 title 文本在小程序最多可显示两行,App仅支持单行显示。
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
static toast(title, duration = 1500, icon = 'none') {
|
||||
return new Promise(function (resolve, reject) {
|
||||
uni.showToast({
|
||||
title: title,
|
||||
icon: icon,
|
||||
mask: true, // 是否显示透明蒙层,防止触摸穿透,默认:false
|
||||
duration: duration, // 提示的延迟时间,单位毫秒,默认:1500
|
||||
complete: () => {
|
||||
setTimeout(function () {
|
||||
resolve('提示时间已完成');
|
||||
}, duration);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完后直接跳转页面
|
||||
*/
|
||||
static toastNavigateTo(title, url, urlParams, objParams) {
|
||||
const _self = this;
|
||||
|
||||
// 兼容部分手机机型不能从导航事件中获取objParams问题。
|
||||
globalVariable.objParams = objParams;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (title) {
|
||||
this.toast(title).then(() => {
|
||||
uni.navigateTo({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams),
|
||||
success: function (res) {
|
||||
if (objParams) {
|
||||
// 通过eventChannel向被打开页面传送数据
|
||||
res.eventChannel.emit('objParams', objParams)
|
||||
}
|
||||
resolve(res);
|
||||
}
|
||||
})
|
||||
})
|
||||
} else {
|
||||
uni.navigateTo({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams),
|
||||
success: function (res) {
|
||||
if (objParams) {
|
||||
// 通过eventChannel向被打开页面传送数据
|
||||
res.eventChannel.emit('objParams', objParams)
|
||||
}
|
||||
resolve(res);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完后直接返回上一个页面
|
||||
*/
|
||||
static toastNavigateBack(title, delta = 1) {
|
||||
const _self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (title) {
|
||||
_self.toast(title).then(() => {
|
||||
uni.navigateBack({
|
||||
delta: delta
|
||||
});
|
||||
resolve();
|
||||
})
|
||||
} else {
|
||||
uni.navigateBack({
|
||||
delta: delta
|
||||
});
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完毕后关闭所有页面并打开指定页面
|
||||
*/
|
||||
static toastReLaunch(title, url, urlParams) {
|
||||
const _self = this;
|
||||
if (title) {
|
||||
_self.toast(title).then(() => {
|
||||
uni.reLaunch({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
})
|
||||
} else {
|
||||
uni.reLaunch({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完毕后跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
|
||||
*/
|
||||
static toastSwitchTab(title, url, urlParams) {
|
||||
const _self = this;
|
||||
if (title) {
|
||||
_self.toast(title).then(() => {
|
||||
uni.switchTab({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
})
|
||||
} else {
|
||||
uni.switchTab({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
{
|
||||
title: '删除图片',
|
||||
content: '确定要删除该图片?',
|
||||
showCancel: true, // 是否显示取消按钮
|
||||
cancelText:"否", // 默认是“取消”
|
||||
cancelColor:'skyblue', // 取消文字的颜色
|
||||
confirmText:"是", // 默认是“确定”
|
||||
confirmColor: 'skyblue', // 确定文字的颜色
|
||||
success: function (res) {
|
||||
if (res.cancel) { // 点击取消,默认隐藏弹框
|
||||
} else { // 点击确定
|
||||
|
||||
temp.splice(index, 1),
|
||||
that.setData({
|
||||
tempFilePaths: temp,
|
||||
})
|
||||
}
|
||||
},
|
||||
fail: function (res) { }, // 接口调用失败的回调函数
|
||||
complete: function (res) { } // 接口调用结束的回调函数(调用成功、失败都会执行)
|
||||
}
|
||||
|
||||
CommonUtil.alert({
|
||||
title: '提示!',
|
||||
content: '确认提交吗?',
|
||||
showCancel: true, // 是否显示取消按钮
|
||||
success: function (res) {
|
||||
if (res.cancel) { // 点击取消,默认隐藏弹框
|
||||
} else { // 点击确定
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
* @param opts
|
||||
*/
|
||||
static alert(opts) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (typeof opts === 'string') {
|
||||
uni.showModal({
|
||||
title: '提示',
|
||||
content: opts,
|
||||
showCancel: false, // 是否显示取消按钮
|
||||
success: function (res) {
|
||||
if (res.cancel) { // 点击取消,默认隐藏弹框
|
||||
} else { // 点击确定
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
uni.showModal(opts);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完后直接跳转页面
|
||||
*/
|
||||
static alertNavigateTo(title, url, urlParams, objParams) {
|
||||
const _self = this;
|
||||
|
||||
// 兼容部分手机机型不能从导航事件中获取objParams问题。
|
||||
globalVariable.objParams = objParams;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (title) {
|
||||
uni.showModal({
|
||||
title: '提示!',
|
||||
content: title,
|
||||
showCancel: false, // 是否显示取消按钮
|
||||
success: function (res) {
|
||||
if (res.cancel) { // 点击取消,默认隐藏弹框
|
||||
} else { // 点击确定
|
||||
uni.navigateTo({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams),
|
||||
success: function (res) {
|
||||
if (objParams) {
|
||||
// 通过eventChannel向被打开页面传送数据
|
||||
res.eventChannel.emit('objParams', objParams)
|
||||
}
|
||||
resolve(res);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
uni.navigateTo({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams),
|
||||
success: function (res) {
|
||||
if (objParams) {
|
||||
// 通过eventChannel向被打开页面传送数据
|
||||
res.eventChannel.emit('objParams', objParams)
|
||||
}
|
||||
resolve(res);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完后直接返回上一个页面
|
||||
*/
|
||||
static alertNavigateBack(title, delta = 1) {
|
||||
const _self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (title) {
|
||||
uni.showModal({
|
||||
title: '提示!',
|
||||
content: title,
|
||||
showCancel: false, // 是否显示取消按钮
|
||||
success: function (res) {
|
||||
if (res.cancel) { // 点击取消,默认隐藏弹框
|
||||
} else { // 点击确定
|
||||
uni.navigateBack({
|
||||
delta: delta
|
||||
});
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
uni.navigateBack({
|
||||
delta: delta
|
||||
});
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完毕后关闭所有页面并打开指定页面
|
||||
*/
|
||||
static alertReLaunch(title, url, urlParams) {
|
||||
const _self = this;
|
||||
if (title) {
|
||||
uni.showModal({
|
||||
title: '提示!',
|
||||
content: title,
|
||||
showCancel: false, // 是否显示取消按钮
|
||||
success: function (res) {
|
||||
if (res.cancel) { // 点击取消,默认隐藏弹框
|
||||
} else { // 点击确定
|
||||
uni.reLaunch({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
uni.reLaunch({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行完毕后跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
|
||||
*/
|
||||
static alertSwitchTab(title, url, urlParams) {
|
||||
const _self = this;
|
||||
if (title) {
|
||||
uni.showModal({
|
||||
title: '提示!',
|
||||
content: title,
|
||||
showCancel: false, // 是否显示取消按钮
|
||||
success: function (res) {
|
||||
if (res.cancel) { // 点击取消,默认隐藏弹框
|
||||
} else { // 点击确定
|
||||
uni.switchTab({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
uni.switchTab({
|
||||
url: _self.urlParamsAppendToUrl(url, urlParams)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
全局引入方式:src/main.js
|
||||
|
||||
import * as filters from './app/core/utils/filters.util' // global filters
|
||||
|
||||
// 注册全局的过滤器,在页面上直接使用无须再显示定义过滤器
|
||||
Object.keys(filters).forEach(key => {
|
||||
Vue.filter(key, filters[key])
|
||||
})
|
||||
|
||||
使用方式:在页面中直接使用
|
||||
<template>
|
||||
{{'abc' | uppercaseFirst}}
|
||||
</template>
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Parse the time to string
|
||||
* @param {(Object|string|number)} time
|
||||
* @param {string} cFormat
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function parseTime(time, cFormat) {
|
||||
if (arguments.length === 0 || !time) {
|
||||
return null
|
||||
}
|
||||
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
|
||||
let date
|
||||
if (typeof time === 'object') {
|
||||
date = time
|
||||
} else {
|
||||
if ((typeof time === 'string')) {
|
||||
if ((/^[0-9]+$/.test(time))) {
|
||||
// support "1548221490638"
|
||||
time = parseInt(time)
|
||||
} else {
|
||||
// support safari
|
||||
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
|
||||
time = time.replace(new RegExp(/-/gm), '/')
|
||||
}
|
||||
}
|
||||
|
||||
if ((typeof time === 'number') && (time.toString().length === 10)) {
|
||||
time = time * 1000
|
||||
}
|
||||
date = new Date(time)
|
||||
}
|
||||
const formatObj = {
|
||||
y: date.getFullYear(),
|
||||
m: date.getMonth() + 1,
|
||||
d: date.getDate(),
|
||||
h: date.getHours(),
|
||||
i: date.getMinutes(),
|
||||
s: date.getSeconds(),
|
||||
a: date.getDay()
|
||||
}
|
||||
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
|
||||
const value = formatObj[key]
|
||||
// Note: getDay() returns 0 on Sunday
|
||||
if (key === 'a') {
|
||||
return ['日', '一', '二', '三', '四', '五', '六'][value]
|
||||
}
|
||||
return value.toString().padStart(2, '0')
|
||||
})
|
||||
return time_str
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} time
|
||||
* @param {string} option
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatTime(time, option) {
|
||||
if (('' + time).length === 10) {
|
||||
time = parseInt(time) * 1000
|
||||
} else {
|
||||
time = +time
|
||||
}
|
||||
const d = new Date(time)
|
||||
const now = Date.now()
|
||||
|
||||
const diff = (now - d) / 1000
|
||||
|
||||
if (diff < 30) {
|
||||
return '刚刚'
|
||||
} else if (diff < 3600) {
|
||||
// less 1 hour
|
||||
return Math.ceil(diff / 60) + '分钟前'
|
||||
} else if (diff < 3600 * 24) {
|
||||
return Math.ceil(diff / 3600) + '小时前'
|
||||
} else if (diff < 3600 * 24 * 2) {
|
||||
return '1天前'
|
||||
}
|
||||
if (option) {
|
||||
return parseTime(time, option)
|
||||
} else {
|
||||
return (
|
||||
d.getMonth() +
|
||||
1 +
|
||||
'月' +
|
||||
d.getDate() +
|
||||
'日' +
|
||||
d.getHours() +
|
||||
'时' +
|
||||
d.getMinutes() +
|
||||
'分'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @returns {Object}
|
||||
*/
|
||||
export function param2Obj(url) {
|
||||
const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
|
||||
if (!search) {
|
||||
return {}
|
||||
}
|
||||
const obj = {}
|
||||
const searchArr = search.split('&')
|
||||
searchArr.forEach(v => {
|
||||
const index = v.indexOf('=')
|
||||
if (index !== -1) {
|
||||
const name = v.substring(0, index)
|
||||
const val = v.substring(index + 1, v.length)
|
||||
obj[name] = val
|
||||
}
|
||||
})
|
||||
return obj
|
||||
}
|
||||
|
||||
/**
|
||||
* Show plural label if time is plural number
|
||||
* @param {number} time
|
||||
* @param {string} label
|
||||
* @return {string}
|
||||
*/
|
||||
function pluralize(time, label) {
|
||||
if (time === 1) {
|
||||
return time + label
|
||||
}
|
||||
return time + label + 's'
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} time
|
||||
*/
|
||||
export function timeAgo(time) {
|
||||
const between = Date.now() / 1000 - Number(time)
|
||||
if (between < 3600) {
|
||||
return pluralize(~~(between / 60), ' minute')
|
||||
} else if (between < 86400) {
|
||||
return pluralize(~~(between / 3600), ' hour')
|
||||
} else {
|
||||
return pluralize(~~(between / 86400), ' day')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number formatting
|
||||
* like 10000 => 10k
|
||||
* @param {number} num
|
||||
* @param {number} digits
|
||||
*/
|
||||
export function numberFormatter(num, digits) {
|
||||
const si = [
|
||||
{value: 1E18, symbol: 'E'},
|
||||
{value: 1E15, symbol: 'P'},
|
||||
{value: 1E12, symbol: 'T'},
|
||||
{value: 1E9, symbol: 'G'},
|
||||
{value: 1E6, symbol: 'M'},
|
||||
{value: 1E3, symbol: 'k'}
|
||||
]
|
||||
for (let i = 0; i < si.length; i++) {
|
||||
if (num >= si[i].value) {
|
||||
return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
|
||||
}
|
||||
}
|
||||
return num.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* 10000 => "10,000"
|
||||
* @param {number} num
|
||||
*/
|
||||
export function toThousandFilter(num) {
|
||||
return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
|
||||
}
|
||||
|
||||
/**
|
||||
* Upper case first char
|
||||
* @param {String} string
|
||||
*/
|
||||
export function uppercaseFirst(string) {
|
||||
return string.charAt(0).toUpperCase() + string.slice(1)
|
||||
}
|
||||
|
||||
/**
|
||||
* 保留两位小数点
|
||||
* @param value
|
||||
* @returns {*|string}
|
||||
*/
|
||||
export function toFixed2(value) {
|
||||
let result = ''
|
||||
if (value) {
|
||||
// 截取当前数据到小数点后两位
|
||||
result = value.toFixed(2)
|
||||
} else {
|
||||
result = '0.00'
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 保留小数点位数
|
||||
* @param value
|
||||
* @param retain 保留小数点位数
|
||||
* @returns {*|string}
|
||||
*/
|
||||
export function toFixed(value, retain = 0) {
|
||||
let result = ''
|
||||
if (value) {
|
||||
// 截取当前数据到小数点后两位
|
||||
result = value.toFixed(retain)
|
||||
} else {
|
||||
result = 0.0.toFixed(retain);
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果是null,则显示成空字符串
|
||||
* @param value
|
||||
* @param defaultValue
|
||||
* @returns {string}
|
||||
*/
|
||||
export function toEmptyStr(value, defaultValue) {
|
||||
value = value + '' // 转成字符串,数字没有.replace方法。
|
||||
if (value === null || value === undefined || value === 'null' || value === 'undefined' || value.replace(/(^\s*)|(\s*$)/g, '') === '') {
|
||||
if (defaultValue) {
|
||||
return defaultValue
|
||||
}
|
||||
return ''
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台返回的base64字符串图片前端不能显示,需要使用这个过滤器后才能显示出来
|
||||
* @param value
|
||||
* @returns {*}
|
||||
*/
|
||||
export function captchaSrc(value) {
|
||||
let result = ''
|
||||
if (value) {
|
||||
return value.replace(/[\r\n]/g, '')
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出对象某个属性值,如果属性不存在则返回null,防止a.b.c时a或b为null输出属性c报错。
|
||||
* @param value 实际对象需要调用的属性字符串形式
|
||||
* @param target 实际对象
|
||||
* @param defaultValue 如果对象中间的某个属性不存在则会报错,则返回默认值
|
||||
* @returns {*}
|
||||
*
|
||||
* 使用方式:
|
||||
* 过滤器作用:{{'selectedItem.code' | toValue(selectedItem)}}
|
||||
* 当普通函数使用:{{toValue('selectedItem.code', selectedItem) + 'abc'}} // 需要在src/main.js配置Vue.prototype[key] = filters[key]
|
||||
*/
|
||||
export function toValue(value, target, defaultValue = null) {
|
||||
if (!target) {
|
||||
return defaultValue
|
||||
}
|
||||
let attrs = value.split('.')
|
||||
let clone = Object.assign({}, target)
|
||||
for (let i = 1; i < attrs.length; i++) {
|
||||
let attr = attrs[i]
|
||||
if (i < attrs.length - 1) {
|
||||
if (!clone[attr]) {
|
||||
return defaultValue
|
||||
} else {
|
||||
clone = clone[attr]
|
||||
}
|
||||
} else {
|
||||
return clone[attr]
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import Vue from 'vue'
|
||||
import globalVariable from "../global-variable";
|
||||
|
||||
/**
|
||||
* todo 网络超时设置方式:https://uniapp.dcloud.net.cn/collocation/manifest?id=networktimeout
|
||||
* 在配置文件manifest.json中配置
|
||||
* "networkTimeout":{
|
||||
* "request": 600000 单位/毫秒
|
||||
* },
|
||||
* "app-plus" : {
|
||||
* }
|
||||
*/
|
||||
export class HttpUtil {
|
||||
|
||||
/**
|
||||
* 版本: ‘develop’, //开发版
|
||||
* 版本: ‘trial’, //体验版
|
||||
* 版本: ‘release’, //正式版
|
||||
*/
|
||||
static appendProfilesActive(params) {
|
||||
let profilesActive = '';
|
||||
if (this.__wxConfig) {
|
||||
if (__wxConfig.envVersion === 'develop') {
|
||||
profilesActive = 'dev';
|
||||
} else if (__wxConfig.envVersion === 'trial') {
|
||||
profilesActive = 'dev'; // test
|
||||
} else if (__wxConfig.envVersion === 'release') {
|
||||
profilesActive = 'prod';
|
||||
}
|
||||
if (params.data) {
|
||||
params.data.profilesActive = profilesActive;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static getRequestParams(params) {
|
||||
if (params) {
|
||||
if (typeof params === 'string') {
|
||||
params = {url: params}
|
||||
}
|
||||
|
||||
if (params.url.indexOf('http') === -1) {
|
||||
params.url = globalVariable.baseUrl + params.url
|
||||
}
|
||||
|
||||
// this.appendProfilesActive(params);
|
||||
|
||||
let data = params.data;
|
||||
if (!data) {
|
||||
params.data = {};
|
||||
return params
|
||||
}
|
||||
|
||||
// 删除data参数中值为null或者空字符串或者是undefined的属性。
|
||||
if (params.isOptimizeData !== false) { // 是否优化参数
|
||||
// 对于更新的请求,不显示优化属性的话,一般不删除空字符串的属性。
|
||||
if (params.url.substring(params.url.lastIndexOf('/') + 1).indexOf('update') === 0 && params.isOptimizeData !== true) {
|
||||
return params
|
||||
}
|
||||
for (let attrName in data) {
|
||||
if (data[attrName] === undefined
|
||||
|| data[attrName] == null
|
||||
|| data[attrName] === 'undefined'
|
||||
|| data[attrName] === 'null'
|
||||
|| (data[attrName] + '').trim() === '') {
|
||||
delete data[attrName]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
/**
|
||||
* post请求时将url附加的参数追加到data中
|
||||
* 2020-8-31 17:12:45 uView框架post请求url附加参数会报错,运行时就卡死。
|
||||
* @param params
|
||||
*/
|
||||
static urlParamsToData(params) {
|
||||
if (params.url.indexOf("?") !== -1) { // url=test?a=1&b=2
|
||||
let url = params.url.substring(0, params.url.indexOf("?")); // url=test
|
||||
let keyValueStr = params.url.substring(params.url.indexOf("?") + 1); // keyValueStr -> a=1&b=2
|
||||
let keyValueList = keyValueStr.split("&"); // keyValueList=["a=1", "b=2"]
|
||||
// 去掉url中的参数
|
||||
params.url = url;
|
||||
// 将url中的参数追加到data中
|
||||
keyValueList.forEach((value, index) => {
|
||||
// todo 覆盖data中同属性值
|
||||
params.data[value.split("=")[0]] = value.split("=")[1]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static myGet(params) {
|
||||
const _self = this;
|
||||
params = _self.getRequestParams(params);
|
||||
return Vue.prototype.$u.get(params.url, params.data)
|
||||
}
|
||||
|
||||
static myPost(params) {
|
||||
const _self = this;
|
||||
params = _self.getRequestParams(params);
|
||||
_self.urlParamsToData(params);
|
||||
return Vue.prototype.$u.post(params.url, params.data, {
|
||||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
|
||||
})
|
||||
}
|
||||
|
||||
static myPostJson(params) {
|
||||
const _self = this;
|
||||
params = _self.getRequestParams(params);
|
||||
_self.urlParamsToData(params);
|
||||
return Vue.prototype.$u.post(params.url, params.data, {
|
||||
'content-type': 'application/json; charset=UTF-8'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import globalVariable from "../global-variable";
|
||||
|
||||
/**
|
||||
* 本地存储工具类
|
||||
*/
|
||||
export class LocalStorageUtil {
|
||||
|
||||
static setItem(key, value) {
|
||||
let v = null;
|
||||
if (typeof (value) == 'object') {
|
||||
v = JSON.stringify(value);
|
||||
} else {
|
||||
v = value;
|
||||
}
|
||||
try {
|
||||
key = globalVariable.localStoragePrefix + key;
|
||||
console.log('存储【' + key + '】值: ', v);
|
||||
uni.setStorageSync(key, v);
|
||||
} catch (e) {
|
||||
console.log('存储【' + key + '】失败');
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
static getItem(key) {
|
||||
key = globalVariable.localStoragePrefix + key;
|
||||
let value = null;
|
||||
try {
|
||||
value = uni.getStorageSync(key);
|
||||
if (value) {
|
||||
value = JSON.parse(value);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
console.log('获取【' + key + '】值: ', value);
|
||||
} catch (e) {
|
||||
console.log('存储的值不是对象类型: ', value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static removeItem(key) {
|
||||
try {
|
||||
key = globalVariable.localStoragePrefix + key;
|
||||
uni.removeStorageSync(key);
|
||||
console.log('移除【' + key + '】成功')
|
||||
} catch (e) {
|
||||
console.log('移除【' + key + '】失败')
|
||||
}
|
||||
}
|
||||
|
||||
static setOrGetItem(key, value) {
|
||||
if (value && (JSON.stringify(value) + '') != '{}') {
|
||||
return this.setItem(key, value)
|
||||
} else {
|
||||
return this.getItem(key)
|
||||
}
|
||||
}
|
||||
|
||||
static setOrGetQueryParams(page, params) {
|
||||
const _self = this
|
||||
// let className = page.__proto__.constructor.name; // 返回上一级时手机端this还是子对象,导致返回上级页面时获取的是子页面的数据,导致错误。
|
||||
let className = page
|
||||
console.log(className + '导航参数---------------' + JSON.stringify(params))
|
||||
let result = _self.setOrGetItem(`navParams${className}`, params)
|
||||
if (!result) {
|
||||
result = {}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,667 @@
|
||||
import {HttpUtil} from "./http.util";
|
||||
import globalVariable from "../global-variable";
|
||||
import {WechatService} from "../../services/wechat.service";
|
||||
import {LocalStorageUtil} from "./local-storage.util";
|
||||
|
||||
/**
|
||||
* 初始化支付环境
|
||||
*/
|
||||
export function initPayEnvironment() {
|
||||
const _self = this;
|
||||
console.log("globalVariable---------------------", globalVariable);
|
||||
return new Promise(function (resolve, reject) {
|
||||
// 微信小程序版-微信支付
|
||||
if (globalVariable.runPlatform === "0") {
|
||||
console.log("准备获得微信小程序code");
|
||||
|
||||
// 如果没有openid则无法支付,需要先授权获取unionid
|
||||
if (!globalVariable.userInfo.unionid) {
|
||||
new WechatService().findUnionidByWeixinMiniAppCode().then(result => {
|
||||
globalVariable.userInfo.unionid = result.data;
|
||||
LocalStorageUtil.setItem("userInfo", globalVariable.userInfo);
|
||||
resolve('支付环境初始化成功!');
|
||||
})
|
||||
} else {
|
||||
resolve('支付环境初始化成功!');
|
||||
}
|
||||
} else if (globalVariable.runPlatform === "1") {
|
||||
console.log("准备获得微信应用code");
|
||||
|
||||
// 如果没有openid则无法支付,需要先授权获取unionid
|
||||
if (!globalVariable.userInfo.unionid) {
|
||||
new WechatService().findUnionidByWeixinAppCode().then(result => {
|
||||
globalVariable.userInfo.unionid = result.data;
|
||||
LocalStorageUtil.setItem("userInfo", globalVariable.userInfo);
|
||||
resolve('支付环境初始化成功!');
|
||||
})
|
||||
} else {
|
||||
resolve('支付环境初始化成功!');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付订单
|
||||
*/
|
||||
export function pay_order(params) {
|
||||
if (globalVariable.runPlatform === "0") {
|
||||
wxMiniAppPay(params);
|
||||
} else if (globalVariable.runPlatform === "1") {
|
||||
appPay(params);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 充值店铺保证金
|
||||
*/
|
||||
export function pay_tbStoreCashDeposit(params) {
|
||||
if (globalVariable.runPlatform === "0") {
|
||||
wxMiniAppPay_tbStoreCashDeposit(params);
|
||||
} else if (globalVariable.runPlatform === "1") {
|
||||
appPay_tbStoreCashDeposit(params)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 购买邮箱支付码
|
||||
*/
|
||||
export function pay_tbEmailPayCodeOrder(params) {
|
||||
if (globalVariable.runPlatform === "0") {
|
||||
wxMiniAppPay_tbEmailPayCodeOrder(params);
|
||||
} else if (globalVariable.runPlatform === "1") {
|
||||
appPay_tbEmailPayCodeOrder(params)
|
||||
}
|
||||
}
|
||||
|
||||
// todo ------------------------------------------------微信小程序支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信小程序支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信小程序支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信小程序支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信小程序支付------------------------------------------------
|
||||
/**
|
||||
* 微信支付-微信小程序版
|
||||
* @param params
|
||||
*/
|
||||
export function wxMiniAppPay(params) {
|
||||
HttpUtil.myPost({ // 封装微信请求方法
|
||||
url: 'wxPay/miniAppPay',
|
||||
data: {
|
||||
unionid: globalVariable.userInfo.unionid,
|
||||
orderId: params.orderId, // 根据商户自己的秘钥进行支付,后台没有查询到则使用自己默认的。
|
||||
}
|
||||
}).then(result => {
|
||||
// 支付密钥生成成功
|
||||
if (result.code === 0) {
|
||||
|
||||
// 支付密钥生成成功,调起支付功能
|
||||
uni.requestPayment({
|
||||
timeStamp: result.data.timeStamp,
|
||||
nonceStr: result.data.nonceStr,
|
||||
package: result.data.package,
|
||||
signType: result.data.signType,
|
||||
paySign: result.data.paySign,
|
||||
success: (res) => {
|
||||
|
||||
// 支付成功! 请求后台校验是否支付成功
|
||||
HttpUtil.myPost({
|
||||
url: 'wxPay/miniAppPayOrderQuery',
|
||||
data: {
|
||||
orderId: params.orderId
|
||||
}
|
||||
}).then(queryResult => {
|
||||
if (queryResult.code === 0) { // 校验成功/支付成功
|
||||
uni.showToast({
|
||||
title: '支付成功!',
|
||||
icon: 'success',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(queryResult.data)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
})
|
||||
},
|
||||
fail: function (res) {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
complete: function (res) {
|
||||
console.log(res)
|
||||
}
|
||||
})
|
||||
|
||||
} else { // 支付密钥生成失败
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信支付-微信小程序版
|
||||
* 充值店铺保证金
|
||||
*/
|
||||
export function wxMiniAppPay_tbStoreCashDeposit(params) {
|
||||
const _self = this;
|
||||
HttpUtil.myPost({ // 封装微信请求方法
|
||||
url: 'wxPay/miniAppPay_tbStoreCashDeposit',
|
||||
data: {
|
||||
unionid: globalVariable.userInfo.unionid,
|
||||
payMoney: params.payMoney
|
||||
}
|
||||
}).then(result => {
|
||||
|
||||
// 支付密钥生成成功
|
||||
if (result.code === 0) {
|
||||
|
||||
// 支付密钥生成成功,调起支付功能
|
||||
uni.requestPayment({
|
||||
timeStamp: result.data.timeStamp,
|
||||
nonceStr: result.data.nonceStr,
|
||||
package: result.data.package,
|
||||
signType: result.data.signType,
|
||||
paySign: result.data.paySign,
|
||||
success: (res) => {
|
||||
// 支付成功! 请求后台校验是否支付成功
|
||||
HttpUtil.myPost({
|
||||
url: 'wxPay/miniAppPay_tbStoreCashDepositQuery',
|
||||
data: {
|
||||
code: result.data.code, // 订单编号
|
||||
}
|
||||
}).then(queryResult => {
|
||||
if (queryResult.code === 0) { // 校验成功/支付成功
|
||||
uni.showToast({
|
||||
title: '支付成功!',
|
||||
icon: 'success',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(queryResult.data)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
},
|
||||
fail: function (res) {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
complete: function (res) {
|
||||
console.log(res)
|
||||
}
|
||||
})
|
||||
} else { // 支付密钥生成失败
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 微信支付-微信小程序版
|
||||
* 购买邮件支付码
|
||||
*/
|
||||
export function wxMiniAppPay_tbEmailPayCodeOrder(params) {
|
||||
const _self = this;
|
||||
HttpUtil.myPost({ // 封装微信请求方法
|
||||
url: 'wxPay/miniAppPay_tbEmailPayCodeOrder',
|
||||
data: {
|
||||
unionid: globalVariable.userInfo.unionid,
|
||||
email: params.email,
|
||||
type: params.type,
|
||||
}
|
||||
}).then(result => {
|
||||
|
||||
// 支付密钥生成成功
|
||||
if (result.code === 0) {
|
||||
|
||||
// 支付密钥生成成功,调起支付功能
|
||||
uni.requestPayment({
|
||||
timeStamp: result.data.timeStamp,
|
||||
nonceStr: result.data.nonceStr,
|
||||
package: result.data.package,
|
||||
signType: result.data.signType,
|
||||
paySign: result.data.paySign,
|
||||
success: (res) => {
|
||||
// 支付成功! 请求后台校验是否支付成功
|
||||
HttpUtil.myPost({
|
||||
url: 'wxPay/miniAppPay_tbEmailPayCodeOrderQuery',
|
||||
data: {
|
||||
code: result.data.code, // 订单编号
|
||||
}
|
||||
}).then(queryResult => {
|
||||
if (queryResult.code === 0) { // 校验成功/支付成功
|
||||
uni.showToast({
|
||||
title: '支付成功!',
|
||||
icon: 'success',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(queryResult.data)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
},
|
||||
fail: function (res) {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
complete: function (res) {
|
||||
console.log(res)
|
||||
}
|
||||
})
|
||||
} else { // 支付密钥生成失败
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// todo ------------------------------------------------微信APP支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信APP支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信APP支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信APP支付------------------------------------------------
|
||||
// todo ------------------------------------------------微信APP支付------------------------------------------------
|
||||
/**
|
||||
* 微信支付-微信小程序版
|
||||
* 订单支付
|
||||
* @param params
|
||||
*/
|
||||
export function appPay(params) {
|
||||
HttpUtil.myPost({ // 封装微信请求方法
|
||||
url: 'wxPay/appPay',
|
||||
data: {
|
||||
unionid: globalVariable.userInfo.unionid,
|
||||
orderId: params.orderId, // 根据商户自己的秘钥进行支付,后台没有查询到则使用自己默认的。
|
||||
}
|
||||
}).then(result => {
|
||||
// 支付密钥生成成功
|
||||
if (result.code === 0) {
|
||||
// 支付密钥生成成功,调起支付功能
|
||||
uni.requestPayment({
|
||||
provider: 'wxpay',
|
||||
orderInfo: { //微信、支付宝订单数据
|
||||
appid: result.data.appid,
|
||||
noncestr: result.data.noncestr,
|
||||
package: result.data.package, // 固定值,以微信支付文档为主
|
||||
partnerid: result.data.partnerid,
|
||||
prepayid: result.data.prepayid,
|
||||
timestamp: result.data.timestamp,
|
||||
sign: result.data.sign // 根据签名算法生成签名
|
||||
},
|
||||
success: (res) => {
|
||||
|
||||
// 支付成功! 请求后台校验是否支付成功
|
||||
HttpUtil.myPost({
|
||||
url: 'wxPay/appPayOrderQuery',
|
||||
data: {
|
||||
orderId: params.orderId
|
||||
}
|
||||
}).then(queryResult => {
|
||||
if (queryResult.code === 0) { // 校验成功/支付成功
|
||||
uni.showToast({
|
||||
title: '支付成功!',
|
||||
icon: 'success',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(queryResult.data)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
})
|
||||
},
|
||||
fail: function (res) {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
complete: function (res) {
|
||||
console.log(res)
|
||||
}
|
||||
})
|
||||
|
||||
} else { // 支付密钥生成失败
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信支付-微信小程序版
|
||||
* 充值店铺保证金
|
||||
*/
|
||||
export function appPay_tbStoreCashDeposit(params) {
|
||||
const _self = this;
|
||||
HttpUtil.myPost({ // 封装微信请求方法
|
||||
url: 'wxPay/appPay_tbStoreCashDeposit',
|
||||
data: {
|
||||
unionid: globalVariable.userInfo.unionid,
|
||||
payMoney: params.payMoney
|
||||
}
|
||||
}).then(result => {
|
||||
|
||||
// 支付密钥生成成功
|
||||
if (result.code === 0) {
|
||||
// 支付密钥生成成功,调起支付功能
|
||||
uni.requestPayment({
|
||||
provider: 'wxpay',
|
||||
orderInfo: { //微信、支付宝订单数据
|
||||
appid: result.data.appid,
|
||||
noncestr: result.data.noncestr,
|
||||
package: result.data.package, // 固定值,以微信支付文档为主
|
||||
partnerid: result.data.partnerid,
|
||||
prepayid: result.data.prepayid,
|
||||
timestamp: result.data.timestamp,
|
||||
sign: result.data.sign // 根据签名算法生成签名
|
||||
},
|
||||
success: (res) => {
|
||||
// 支付成功! 请求后台校验是否支付成功
|
||||
HttpUtil.myPost({
|
||||
url: 'wxPay/appPay_tbStoreCashDepositQuery',
|
||||
data: {
|
||||
code: result.data.code, // 订单编号
|
||||
}
|
||||
}).then(queryResult => {
|
||||
if (queryResult.code === 0) { // 校验成功/支付成功
|
||||
uni.showToast({
|
||||
title: '支付成功!',
|
||||
icon: 'success',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(queryResult.data)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
},
|
||||
fail: function (res) {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
complete: function (res) {
|
||||
console.log(res)
|
||||
}
|
||||
})
|
||||
} else { // 支付密钥生成失败
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 微信支付-微信小程序版
|
||||
* 购买邮件支付码
|
||||
*/
|
||||
export function appPay_tbEmailPayCodeOrder(params) {
|
||||
const _self = this;
|
||||
HttpUtil.myPost({ // 封装微信请求方法
|
||||
url: 'wxPay/appPay_tbEmailPayCodeOrder',
|
||||
data: {
|
||||
unionid: globalVariable.userInfo.unionid,
|
||||
email: params.email,
|
||||
type: params.type,
|
||||
}
|
||||
}).then(result => {
|
||||
|
||||
// 支付密钥生成成功
|
||||
if (result.code === 0) {
|
||||
// 支付密钥生成成功,调起支付功能
|
||||
uni.requestPayment({
|
||||
provider: 'wxpay',
|
||||
orderInfo: { //微信、支付宝订单数据
|
||||
appid: result.data.appid,
|
||||
noncestr: result.data.noncestr,
|
||||
package: result.data.package, // 固定值,以微信支付文档为主
|
||||
partnerid: result.data.partnerid,
|
||||
prepayid: result.data.prepayid,
|
||||
timestamp: result.data.timestamp,
|
||||
sign: result.data.sign // 根据签名算法生成签名
|
||||
},
|
||||
success: (res) => {
|
||||
// 支付成功! 请求后台校验是否支付成功
|
||||
HttpUtil.myPost({
|
||||
url: 'wxPay/appPay_tbEmailPayCodeOrderQuery',
|
||||
data: {
|
||||
code: result.data.code, // 订单编号
|
||||
}
|
||||
}).then(queryResult => {
|
||||
if (queryResult.code === 0) { // 校验成功/支付成功
|
||||
uni.showToast({
|
||||
title: '支付成功!',
|
||||
icon: 'success',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(queryResult.data)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
},
|
||||
fail: function (res) {
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
mask: true,
|
||||
duration: 1500,
|
||||
complete: () => {
|
||||
if (params.callback) {
|
||||
setTimeout(() => {
|
||||
params.callback(null)
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
complete: function (res) {
|
||||
console.log(res)
|
||||
}
|
||||
})
|
||||
} else { // 支付密钥生成失败
|
||||
uni.showToast({
|
||||
title: '支付失败!',
|
||||
icon: 'warn',
|
||||
duration: 1500,
|
||||
mask: true,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import {CommonService} from "../../services/common.service";
|
||||
import {CommonUtil} from "./common.util";
|
||||
import {HttpUtil} from "./http.util";
|
||||
|
||||
const qiniuUploader = require("./qiniuUploader");
|
||||
|
||||
/**
|
||||
* 七牛云工具类
|
||||
*/
|
||||
export class QiniuCloudUtil {
|
||||
|
||||
static base64Encode(str) {
|
||||
// 对字符串进行编码
|
||||
var encode = encodeURI(str);
|
||||
// 对编码的字符串转化base64
|
||||
// var base64 = btoa(encode); // 微信小程序不支持
|
||||
var base64 = CommonUtil.toBase64Encode(encode);
|
||||
return base64;
|
||||
}
|
||||
|
||||
/**
|
||||
* 帮助文档:https://github.com/gpake/qiniu-wxapp-sdk
|
||||
* @param params
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
static upload(params) {
|
||||
const _self = this;
|
||||
if (!params.id) {
|
||||
params.id = CommonUtil.generateUUID();
|
||||
}
|
||||
return new Promise(function (resolve, reject) {
|
||||
new CommonService().findQiNiuUploadToken().then(result => {
|
||||
// 交给七牛上传
|
||||
qiniuUploader.upload(params.filePath,
|
||||
(res) => { // todo 上传成功
|
||||
// 每个文件上传成功后,处理相关的事情
|
||||
// 其中 info 是文件上传成功后,服务端返回的json,形式如
|
||||
// {
|
||||
// "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
|
||||
// "key": "gogopher.jpg"
|
||||
// }
|
||||
// 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
|
||||
console.log('file url is: ' + res.fileUrl);
|
||||
resolve({
|
||||
id: params.id,
|
||||
status: "success"
|
||||
});
|
||||
}, (error) => { // todo 上传失败
|
||||
console.log('error: ' + error);
|
||||
resolve({
|
||||
id: params.id,
|
||||
status: "fail"
|
||||
});
|
||||
},
|
||||
{
|
||||
region: 'SCN', // qiniuUploader.js文件 uploadURLFromRegionCode 方法可以看到
|
||||
domain: 'http://image.xxxxxxx.com', // // bucket 域名,下载资源时用到。如果设置,会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
|
||||
key: params.id, // todo 对应sysFile主键 [非必须]自定义文件 key。如果不设置,默认为使用微信小程序 API 的临时文件名
|
||||
// 以下方法三选一即可,优先级为:uptoken > uptokenURL > uptokenFunc
|
||||
uptoken: result.token, // 由其他程序生成七牛 uptoken
|
||||
}, (res) => {
|
||||
console.log('上传进度', res.progress)
|
||||
console.log('已经上传的数据长度', res.totalBytesSent)
|
||||
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
|
||||
}, () => {
|
||||
// 取消上传
|
||||
}, () => {
|
||||
// `before` 上传前执行的操作
|
||||
}, (err) => {
|
||||
// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片上传到七牛云,并将上传的图片id保存到后台服务端。
|
||||
* @param fkId sysFile表的外键fkId
|
||||
* @param filePath 图片路径
|
||||
* @param data
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
static uploadToCloud(fkId, filePath, data = {clearOldImage: true, typeMark: "thumbnail"}) {
|
||||
const _self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
_self.upload({
|
||||
filePath: filePath
|
||||
}).then(qiniuCloudResult => {
|
||||
console.log(qiniuCloudResult);
|
||||
if (qiniuCloudResult.status === "success") {
|
||||
HttpUtil.myPost({
|
||||
url: `sysfile/saveBase64Image`,
|
||||
data: {
|
||||
id: qiniuCloudResult.id,
|
||||
name: "移动端上传的图片",
|
||||
fkId: fkId,
|
||||
type: 'image/jpeg',
|
||||
clearOldImage: data.clearOldImage,
|
||||
typeMark: data.typeMark,
|
||||
content: "jsUploaded" // 在js端就将图片上传到七牛云了
|
||||
}
|
||||
}).then(result => {
|
||||
/*let 后台返回 = {
|
||||
id: "sysFile.id",
|
||||
sysFile: sysFile,
|
||||
status: "success"
|
||||
};*/
|
||||
result.message = "上传图片成功";
|
||||
resolve(result);
|
||||
});
|
||||
} else {
|
||||
resolve({
|
||||
status: "fail",
|
||||
message: "上传图片失败"
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// created by gpake
|
||||
(function() {
|
||||
|
||||
var config = {
|
||||
qiniuRegion: '',
|
||||
qiniuImageURLPrefix: '',
|
||||
qiniuUploadToken: '',
|
||||
qiniuUploadTokenURL: '',
|
||||
qiniuUploadTokenFunction: null,
|
||||
qiniuShouldUseQiniuFileName: false
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
init: init,
|
||||
upload: upload,
|
||||
}
|
||||
|
||||
// 在整个程序生命周期中,只需要 init 一次即可
|
||||
// 如果需要变更参数,再调用 init 即可
|
||||
function init(options) {
|
||||
config = {
|
||||
qiniuRegion: '',
|
||||
qiniuImageURLPrefix: '',
|
||||
qiniuUploadToken: '',
|
||||
qiniuUploadTokenURL: '',
|
||||
qiniuUploadTokenFunction: null,
|
||||
qiniuShouldUseQiniuFileName: false
|
||||
};
|
||||
updateConfigWithOptions(options);
|
||||
}
|
||||
|
||||
function updateConfigWithOptions(options) {
|
||||
if (options.region) {
|
||||
config.qiniuRegion = options.region;
|
||||
} else {
|
||||
console.error('qiniu uploader need your bucket region');
|
||||
}
|
||||
if (options.uptoken) {
|
||||
config.qiniuUploadToken = options.uptoken;
|
||||
} else if (options.uptokenURL) {
|
||||
config.qiniuUploadTokenURL = options.uptokenURL;
|
||||
} else if(options.uptokenFunc) {
|
||||
config.qiniuUploadTokenFunction = options.uptokenFunc;
|
||||
}
|
||||
if (options.domain) {
|
||||
config.qiniuImageURLPrefix = options.domain;
|
||||
}
|
||||
config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
|
||||
}
|
||||
|
||||
function upload(filePath, success, fail, options, progress, cancelTask, before, complete) {
|
||||
if (null == filePath) {
|
||||
console.error('qiniu uploader need filePath to upload');
|
||||
return;
|
||||
}
|
||||
if (options) {
|
||||
updateConfigWithOptions(options);
|
||||
}
|
||||
if (config.qiniuUploadToken) {
|
||||
doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
|
||||
} else if (config.qiniuUploadTokenURL) {
|
||||
getQiniuToken(function() {
|
||||
doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
|
||||
});
|
||||
} else if (config.qiniuUploadTokenFunction) {
|
||||
config.qiniuUploadToken = config.qiniuUploadTokenFunction();
|
||||
if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
|
||||
console.error('qiniu UploadTokenFunction result is null, please check the return value');
|
||||
return
|
||||
}
|
||||
doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
|
||||
} else {
|
||||
console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function doUpload(filePath, success, fail, options, progress, cancelTask, before, complete) {
|
||||
if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
|
||||
console.error('qiniu UploadToken is null, please check the init config or networking');
|
||||
return
|
||||
}
|
||||
var url = uploadURLFromRegionCode(config.qiniuRegion);
|
||||
var fileName = filePath.split('//')[1];
|
||||
if (options && options.key) {
|
||||
fileName = options.key;
|
||||
}
|
||||
var formData = {
|
||||
'token': config.qiniuUploadToken
|
||||
};
|
||||
if (!config.qiniuShouldUseQiniuFileName) {
|
||||
formData['key'] = fileName
|
||||
}
|
||||
before && before();
|
||||
var uploadTask = wx.uploadFile({
|
||||
url: url,
|
||||
filePath: filePath,
|
||||
name: 'file',
|
||||
formData: formData,
|
||||
success: function (res) {
|
||||
var dataString = res.data
|
||||
// // this if case is a compatibility with wechat server returned a charcode, but was fixed
|
||||
// if(res.data.hasOwnProperty('type') && res.data.type === 'Buffer'){
|
||||
// dataString = String.fromCharCode.apply(null, res.data.data)
|
||||
// }
|
||||
try {
|
||||
var dataObject = JSON.parse(dataString);
|
||||
//do something
|
||||
var fileUrl = config.qiniuImageURLPrefix + '/' + dataObject.key;
|
||||
dataObject.fileUrl = fileUrl
|
||||
dataObject.imageURL = fileUrl;
|
||||
console.log(dataObject);
|
||||
if (success) {
|
||||
success(dataObject);
|
||||
}
|
||||
} catch(e) {
|
||||
console.log('parse JSON failed, origin String is: ' + dataString)
|
||||
if (fail) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
fail: function (error) {
|
||||
console.error(error);
|
||||
if (fail) {
|
||||
fail(error);
|
||||
}
|
||||
},
|
||||
complete: function(err) {
|
||||
complete && complete(err);
|
||||
}
|
||||
})
|
||||
|
||||
uploadTask.onProgressUpdate((res) => {
|
||||
progress && progress(res)
|
||||
})
|
||||
|
||||
cancelTask && cancelTask(() => {
|
||||
uploadTask.abort()
|
||||
})
|
||||
}
|
||||
|
||||
function getQiniuToken(callback) {
|
||||
wx.request({
|
||||
url: config.qiniuUploadTokenURL,
|
||||
success: function (res) {
|
||||
var token = res.data.uptoken;
|
||||
if (token && token.length > 0) {
|
||||
config.qiniuUploadToken = token;
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
} else {
|
||||
console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
|
||||
}
|
||||
},
|
||||
fail: function (error) {
|
||||
console.error('qiniu UploadToken is null, please check the init config or networking: ' + error);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function uploadURLFromRegionCode(code) {
|
||||
var uploadURL = null;
|
||||
switch(code) {
|
||||
case 'ECN': uploadURL = 'https://up.qiniup.com'; break;
|
||||
case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
|
||||
case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
|
||||
case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
|
||||
case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
|
||||
default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
|
||||
}
|
||||
return uploadURL;
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,286 @@
|
||||
import globalVariable from "../global-variable";
|
||||
|
||||
export class TabbarUtil {
|
||||
|
||||
static getTabbar() {
|
||||
let list = [
|
||||
{
|
||||
type: "0",
|
||||
tabbar: [
|
||||
{
|
||||
"componentRef": "indexRef",
|
||||
"text": "首页",
|
||||
"title": globalVariable.userInfo.tbCommunity ? globalVariable.userInfo.tbCommunity.name : '首页',
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/home_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/home_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "goodsClassRef",
|
||||
"text": "分类",
|
||||
"title": "商品分类",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/sort_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/sort.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "shoppingCartRef",
|
||||
"text": "购物车",
|
||||
"title": "购物车",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/cart_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/cart_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "communityDynamicRef",
|
||||
"text": "动态",
|
||||
"title": "商城动态",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/community_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/community_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "personRef",
|
||||
"text": "我的",
|
||||
"title": "我的",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/my_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/my_fill_light.png"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "1",
|
||||
tabbar: [
|
||||
{
|
||||
"componentRef": "indexRef",
|
||||
"text": "首页",
|
||||
"title": globalVariable.userInfo.tbCommunity ? globalVariable.userInfo.tbCommunity.name : '首页',
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "goodsClassRef",
|
||||
"text": "分类",
|
||||
"title": "商品分类",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/sort_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/sort.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "shoppingCartRef",
|
||||
"text": "购物车",
|
||||
"title": "购物车",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "personRef",
|
||||
"text": "我的",
|
||||
"title": "我的",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_fill_light.png"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "2",
|
||||
tabbar: [
|
||||
{
|
||||
"componentRef": "indexRef",
|
||||
"text": "首页",
|
||||
"title": globalVariable.userInfo.tbCommunity ? globalVariable.userInfo.tbCommunity.name : '首页',
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "goodsClassRef",
|
||||
"text": "分类",
|
||||
"title": "商品分类",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/sort_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/sort.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "goodsSeckillRef",
|
||||
"text": "商品秒杀",
|
||||
"title": "商品秒杀",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/seckill_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/seckill_fill.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "shoppingCartRef",
|
||||
"text": "购物车",
|
||||
"title": "购物车",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "personRef",
|
||||
"text": "我的",
|
||||
"title": "我的",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_fill_light.png"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "3",
|
||||
tabbar: [
|
||||
{
|
||||
"componentRef": "indexEateryRef",
|
||||
"text": "首页",
|
||||
"title": globalVariable.userInfo.tbCommunity ? globalVariable.userInfo.tbCommunity.name : '首页',
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "shoppingCartRef",
|
||||
"text": "购物车",
|
||||
"title": "购物车",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "personRef",
|
||||
"text": "我的",
|
||||
"title": "我的",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_fill_light.png"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "4",
|
||||
tabbar: [
|
||||
{
|
||||
"componentRef": "indexEateryRef",
|
||||
"text": "首页",
|
||||
"title": globalVariable.userInfo.tbCommunity ? globalVariable.userInfo.tbCommunity.name : '首页',
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "shoppingCartRef",
|
||||
"text": "购物车",
|
||||
"title": "购物车",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "communityDynamicRef",
|
||||
"text": "动态",
|
||||
"title": "商城动态",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/community_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/community_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "personRef",
|
||||
"text": "我的",
|
||||
"title": "我的",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_fill_light.png"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "5",
|
||||
tabbar: [
|
||||
{
|
||||
"componentRef": "indexEateryRef",
|
||||
"text": "首页",
|
||||
"title": globalVariable.userInfo.tbCommunity ? globalVariable.userInfo.tbCommunity.name : '首页',
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "goodsSeckillRef",
|
||||
"text": "商品秒杀",
|
||||
"title": "商品秒杀",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/seckill_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/seckill_fill.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "shoppingCartRef",
|
||||
"text": "购物车",
|
||||
"title": "购物车",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "personRef",
|
||||
"text": "我的",
|
||||
"title": "我的",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_fill_light.png"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "6",
|
||||
tabbar: [
|
||||
{
|
||||
"componentRef": "indexEateryRef",
|
||||
"text": "首页",
|
||||
"title": globalVariable.userInfo.tbCommunity ? globalVariable.userInfo.tbCommunity.name : '首页',
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/home_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "shoppingCartRef",
|
||||
"text": "购物车",
|
||||
"title": "购物车",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/cart_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "goodsSeckillRef",
|
||||
"text": "商品秒杀",
|
||||
"title": "商品秒杀",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/seckill_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/seckill_fill.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "communityDynamicRef",
|
||||
"text": "动态",
|
||||
"title": "商城动态",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/community_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/community_fill_light.png"
|
||||
},
|
||||
{
|
||||
"componentRef": "personRef",
|
||||
"text": "我的",
|
||||
"title": "我的",
|
||||
"iconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_light.png",
|
||||
"selectedIconPath": "/pages/sub/sub1-tabs/static/icon/tabbar/tabs/my_fill_light.png"
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// 更新选中的底部导航栏
|
||||
let tabbar = list[0].tabbar;
|
||||
list.forEach((item, index) => {
|
||||
if (item.type === globalVariable.userInfo.tbCommunity.tabbarType) {
|
||||
tabbar = item.tabbar;
|
||||
}
|
||||
});
|
||||
|
||||
return tabbar;
|
||||
|
||||
/*// 更新选择的底部导航栏tab
|
||||
let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
|
||||
let curRoute = routes[routes.length - 1].route; //获取当前页面路由
|
||||
_self.tabbar.forEach((item, index) => {
|
||||
console.log(item.pagePath, curRoute);
|
||||
if (item.pagePath === curRoute) {
|
||||
_self.current = index;
|
||||
}
|
||||
});
|
||||
|
||||
console.log('TabbarUtil---------------------------------', TabbarUtil.current, TabbarUtil.tabbar);*/
|
||||
}
|
||||
|
||||
static getIndexByComponentRef(componentRef) {
|
||||
const _self = this;
|
||||
let tarbar = _self.getTabbar();
|
||||
tarbar.forEach((item, index) => {
|
||||
if (item.componentRef === componentRef) {
|
||||
return index;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
import {CommonUtil} from "./common.util";
|
||||
|
||||
export class UFormUtil {
|
||||
|
||||
/**
|
||||
* 初始化表单对象
|
||||
* @param validateForm
|
||||
*/
|
||||
static init(validateForm) {
|
||||
// console.log("-------------------------------init-------------------------------", validateForm);
|
||||
// 给表单对象添加controls属性
|
||||
const _self = this;
|
||||
let controls = {};
|
||||
let i = 0;
|
||||
for (let attrName in validateForm.value) {
|
||||
controls[attrName] = {
|
||||
id: CommonUtil.generateUUID(),
|
||||
rawValue: validateForm.value[attrName], // 原始值,可以用重置表单
|
||||
value: validateForm.value, // 引用value对线,可以在control中直接操作value对象
|
||||
timestamp: new Date().getTime() + i++,
|
||||
valueName: attrName,
|
||||
options: [],
|
||||
isShow: false,
|
||||
textDesc: '',
|
||||
defaultIndex: -1,
|
||||
}
|
||||
}
|
||||
|
||||
// 添加重置表单方法
|
||||
validateForm.resetValues = function () {
|
||||
for (let attrName in validateForm.value) {
|
||||
validateForm.value[attrName] = validateForm.controls[attrName].rawValue;
|
||||
if (validateForm.controls[attrName].options) {
|
||||
_self.selectOptions(validateForm.controls[attrName], validateForm.controls[attrName].selectColNums, validateForm.controls[attrName].selectValues);
|
||||
}
|
||||
}
|
||||
console.log("resetValues------------------------", validateForm);
|
||||
};
|
||||
|
||||
// 添加搜索事件
|
||||
validateForm.doSearch = function (_selfVue, dataList, uDropdownRef = 'uDropdown') {
|
||||
console.log(_selfVue)
|
||||
console.log(_selfVue.$refs)
|
||||
if (_selfVue.$refs[uDropdownRef]) {
|
||||
_selfVue.$refs[uDropdownRef].close();
|
||||
}
|
||||
_selfVue.doRefresh(dataList);
|
||||
console.log("doSearch------------------------", validateForm);
|
||||
};
|
||||
|
||||
validateForm.controls = controls;
|
||||
return validateForm;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给表单字段设置默认值
|
||||
* @param validateForm
|
||||
* @param data
|
||||
*/
|
||||
static setDefaultValues(validateForm, data) {
|
||||
console.log("-------------------------------setDefaultValues-------------------------------", validateForm, data);
|
||||
if (data === null || data === undefined) {
|
||||
return;
|
||||
}
|
||||
for (let controlName in validateForm.value) {
|
||||
for (let dataName in data) {
|
||||
if (controlName == dataName) {
|
||||
if (typeof data[dataName] === 'boolean') {
|
||||
validateForm.value[controlName] = data[dataName];
|
||||
validateForm.controls[controlName].rawValue = data[dataName];
|
||||
} else {
|
||||
validateForm.value[controlName] = data[dataName] + ""; // todo 值必须转成字符串类型,表单校验规则数字和字符串类型不兼容。
|
||||
validateForm.controls[controlName].rawValue = data[dataName] + ""; // 原始值,可以用重置表单 todo 值必须转成字符串类型,表单校验规则数字和字符串类型不兼容。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 选择地区回调事件
|
||||
*/
|
||||
static regionConfirm(e, control, provinceName = 'provinceName', cityName = 'cityName', areaName = 'areaName') {
|
||||
console.log(e);
|
||||
let value = control.value;
|
||||
value[control.valueName] = e.province.label + '-' + e.city.label + '-' + e.area.label;
|
||||
value[provinceName] = e.province.label;
|
||||
value[cityName] = e.city.label;
|
||||
value[areaName] = e.area.label;
|
||||
control.isShow = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 选择时间回调事件
|
||||
*/
|
||||
static timeConfirm(e, control) {
|
||||
console.log(e);
|
||||
let value = control.value;
|
||||
let yyyyMMdd = [];
|
||||
if (e.year) {
|
||||
yyyyMMdd.push(e.year);
|
||||
}
|
||||
if (e.month) {
|
||||
yyyyMMdd.push(e.month);
|
||||
}
|
||||
if (e.day) {
|
||||
yyyyMMdd.push(e.day);
|
||||
}
|
||||
let hhmmss = [];
|
||||
if (e.hour) {
|
||||
hhmmss.push(e.hour);
|
||||
}
|
||||
if (e.minute) {
|
||||
hhmmss.push(e.minute);
|
||||
}
|
||||
if (e.second) {
|
||||
hhmmss.push(e.second);
|
||||
}
|
||||
value[control.valueName] = `${yyyyMMdd.join("-")} ${hhmmss.join(":")}`.trim();
|
||||
control.isShow = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param control
|
||||
* @param options
|
||||
* @param colNums 列数
|
||||
* @param values 默认值
|
||||
*/
|
||||
static setOptions(control, options, colNums = 1, values) {
|
||||
console.log("-------------------------------setOptions-------------------------------", control, options, colNums, values);
|
||||
if (colNums === 1) { // 删除第一列的子节点
|
||||
options.forEach((item1, index) => {
|
||||
delete item1.children;
|
||||
});
|
||||
} else if (colNums === 2) { // 删除第二列的子节点
|
||||
options.forEach((item1, index1) => {
|
||||
item1.children.forEach((item2, index2) => {
|
||||
delete item2.children;
|
||||
});
|
||||
});
|
||||
} else if (colNums === 3) { // 删除第三列的子节点
|
||||
options.forEach((item1, index1) => {
|
||||
item1.children.forEach((item2, index2) => {
|
||||
item2.children.forEach((item3, index3) => {
|
||||
delete item3.children;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
control.options = options;
|
||||
control.selectColNums = colNums;
|
||||
control.selectValues = values;
|
||||
this.selectOptions(control, colNums, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中某个控件值
|
||||
*
|
||||
* 模式选择,"single-column"-单列模式,"mutil-column"-多列模式,"mutil-column-auto"-多列联动模式
|
||||
* 三列数据格式
|
||||
* [
|
||||
* {
|
||||
* value: 1,
|
||||
* label: '中国',
|
||||
* children: [
|
||||
* {
|
||||
* value: 2,
|
||||
* label: '广东',
|
||||
* children: [
|
||||
* {
|
||||
* value: 3,
|
||||
* label: '深圳'
|
||||
* },
|
||||
* {
|
||||
* value: 4,
|
||||
* label: '广州'
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
*/
|
||||
static selectOptions(control, colNums, values) {
|
||||
let defaultValue = control.value[control.valueName];
|
||||
if (values) {
|
||||
defaultValue = values;
|
||||
}
|
||||
|
||||
// todo 如果值是boolean类型,则换成1或0
|
||||
if (defaultValue === false || defaultValue === 'false') {
|
||||
defaultValue = "0";
|
||||
} else if (defaultValue === true || defaultValue === 'true') {
|
||||
defaultValue = "1";
|
||||
}
|
||||
|
||||
// 单列模式
|
||||
if (colNums === 1) {
|
||||
control.options.forEach((item, index) => {
|
||||
if (item.label !== undefined && item.value !== undefined) {
|
||||
if (item.value + "" === defaultValue + "") {
|
||||
control.textDesc = item.label;
|
||||
control.defaultIndex = index;
|
||||
control.defaultValue = [index];
|
||||
}
|
||||
} else if (item.code !== undefined && item.name !== undefined) {
|
||||
if (item.code + "" === defaultValue + "") {
|
||||
control.textDesc = item.name;
|
||||
control.defaultIndex = index;
|
||||
control.defaultValue = [index];
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (colNums === 2) {
|
||||
// 一般默认值是第二列的值
|
||||
control.options.forEach((item1, index1) => {
|
||||
item1.children.forEach((item2, index2) => {
|
||||
if (item2.label !== undefined && item2.value !== undefined) {
|
||||
if (item2.value + "" === defaultValue + "") {
|
||||
let labels = [];
|
||||
if (item1.label) {
|
||||
labels.push(item1.label);
|
||||
}
|
||||
if (item2.label) {
|
||||
labels.push(item2.label);
|
||||
}
|
||||
control.textDesc = labels.join("-");
|
||||
control.defaultIndex = index2;
|
||||
control.defaultValue = [index1, index2];
|
||||
}
|
||||
} else if (item2.code !== undefined && item2.name !== undefined) {
|
||||
if (item2.code + "" === defaultValue + "") {
|
||||
let names = [];
|
||||
if (item1.name) {
|
||||
names.push(item1.name);
|
||||
}
|
||||
if (item2.name) {
|
||||
names.push(item2.name);
|
||||
}
|
||||
control.textDesc = names.join("-");
|
||||
control.defaultIndex = index2;
|
||||
control.defaultValue = [index1, index2];
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
} else if (colNums === 3) {
|
||||
// 一般默认值是第三列的值
|
||||
control.options.forEach((item1, index1) => {
|
||||
item1.children.forEach((item2, index2) => {
|
||||
item2.children.forEach((item3, index3) => {
|
||||
if (item3.label !== undefined && item3.value !== undefined) {
|
||||
if (item3.value + "" === defaultValue + "") {
|
||||
let labels = [];
|
||||
if (item1.label) {
|
||||
labels.push(item1.label);
|
||||
}
|
||||
if (item2.label) {
|
||||
labels.push(item2.label);
|
||||
}
|
||||
if (item3.label) {
|
||||
labels.push(item3.label);
|
||||
}
|
||||
control.textDesc = labels.join("-");
|
||||
control.defaultIndex = index3;
|
||||
control.defaultValue = [index1, index2, index3];
|
||||
}
|
||||
} else if (item3.code !== undefined && item3.name !== undefined) {
|
||||
if (item3.code + "" === defaultValue + "") {
|
||||
let names = [];
|
||||
if (item1.name) {
|
||||
names.push(item1.name);
|
||||
}
|
||||
if (item2.name) {
|
||||
names.push(item2.name);
|
||||
}
|
||||
if (item3.name) {
|
||||
names.push(item3.name);
|
||||
}
|
||||
control.textDesc = names.join("-");
|
||||
control.defaultIndex = index3;
|
||||
control.defaultValue = [index1, index2, index3];
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单列下拉选择选中事件
|
||||
*/
|
||||
static selectSingleColumnConfirm($event, control) {
|
||||
console.log($event, control);
|
||||
control.value[control.valueName] = $event[0].value;
|
||||
control.textDesc = $event[0].label;
|
||||
this.selectOptions(control, $event.length);
|
||||
control.isShow = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 多列联动下拉选择选中事件
|
||||
*/
|
||||
static selectMutilColumnConfirm($event, control) {
|
||||
console.log($event, control); // $event = [{label: '', value: ''}, {label: '', value: ''}, ...]
|
||||
control.value[control.valueName] = $event[$event.length - 1].value; // 多列联动,取最后一列的值
|
||||
let labels = [];
|
||||
$event.forEach(item => {
|
||||
if (item.label) {
|
||||
labels.push(item.label);
|
||||
}
|
||||
});
|
||||
control.textDesc = labels.join("-");
|
||||
|
||||
// 解决弹框不会选中问题。
|
||||
this.selectOptions(control, $event.length);
|
||||
control.isShow = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取表单中某个字段
|
||||
* @param formRef this.$refs.uForm
|
||||
* @param prop 'code'
|
||||
* @returns {*}
|
||||
*/
|
||||
static getFormItem(formRef, prop) {
|
||||
if (!formRef) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const list = formRef.fields.filter(item => item.prop === prop);
|
||||
if (list.length) {
|
||||
return list[0];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单个字段,触发单个字段的校验规则
|
||||
* @param formRef this.$refs.uForm
|
||||
* @param prop 'code'
|
||||
*
|
||||
* UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
|
||||
*/
|
||||
static validation(formRef, prop) {
|
||||
const _self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
const item = _self.getFormItem(formRef, prop);
|
||||
item.validation('', error => {
|
||||
if (error) {
|
||||
CommonUtil.toast(error);
|
||||
resolve(false);
|
||||
} else {
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user