123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543 |
- const prePage = (num = 2) => {
- let pages = getCurrentPages();
- let prePage = pages[pages.length - num];
- if (!prePage) {
- return null
- }
- // #ifdef H5
- return prePage;
- // #endif
- return prePage.$vm;
- }
- const rushPrePage = (type = false) => {
- if (type) {
- let pages = getCurrentPages();
- const len = pages.length
- if (len <= 1) {
- return false
- }
- pages.forEach((p, index) => {
- if (index >= len - 1) {
- return false
- }
- var prePage = p.$vm;
- // #ifdef H5
- prePage = p;
- // #endif
- try {
- prePage.loadData('rush')
- prePage.loadPageData()
- } catch (e) {
- //TODO handle the exception
- }
- })
- return
- }
- const pag = prePage()
- if (pag) {
- try {
- pag.loadData('rush')
- pag.loadPageData()
- } catch (e) {
- //TODO handle the exception
- }
- }
- return pag
- }
- // 提示信息
- const toast = (text, duration, mask = false, icon = "", image = "") => {
- uni.showToast({
- title: text || "出错啦~",
- icon: icon ? icon : 'none', // "success" "loading" "none"
- image: image,
- duration: duration || 2000,
- mask
- })
- }
- // 复制信息
- const copy = (str) => {
- return new Promise((resolve, reject) => {
- uni.setClipboardData({
- data: str,
- success: function() {
- resolve()
- },
- fail: function() {
- reject()
- }
- });
- })
- }
- // 拨打电话
- const call = (telNumber) => {
- if (!telNumber) {
- modal({
- content: '无可拨打号码!',
- showCancel: false
- })
- return false
- }
- uni.makePhoneCall({
- phoneNumber: telNumber
- });
- }
- // 确认信息弹框
- const modal = (option = null) => {
- const op = Object.assign({
- title: '提示',
- content: '',
- showCancel: true,
- cancelColor: "#999999",
- confirmColor: "#b7251a", //"#007aff", // "#007aff"
- confirmText: "确定",
- cancelText: "取消"
- }, option)
- return new Promise((resolve, reject) => {
- uni.showModal({
- title: op.title,
- content: op.content,
- showCancel: op.showCancel,
- cancelColor: op.cancelColor,
- confirmColor: op.confirmColor,
- confirmText: op.confirmText,
- cancelText: op.cancelText,
- success: (res) => {
- if (res && res.confirm) {
- resolve(res)
- } else {
- reject(res)
- }
- },
- fail: () => {
- reject()
- }
- })
- })
- }
- // 小程序微信支付
- const wxpay = (data) => {
- return new Promise((resolve, reject) => {
- uni.requestPayment({
- provider: 'wxpay', // 服务提供商
- timeStamp: data.timeStamp, // String(Date.now()), // 时间戳从1970年1月1日至今的秒数,即当前的时间
- nonceStr: data.nonceStr, // 随机字符串,长度为32个字符以下
- package: data.package, // 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=xx
- signType: 'MD5', // 签名算法,暂支持 MD5
- paySign: data.paySign, // 签名
- success: function(res) {
- console.log('success:' + JSON.stringify(res));
- resolve(res)
- },
- fail: function(err) {
- console.log('fail:' + JSON.stringify(err));
- reject(err)
- }
- });
- });
- }
- //判断是否登录
- const isLogin = (type = false) => {
- const token = uni.getStorageSync("token") ? true : false
- const url = getApp().globalData.loginPage
- if (type && !token) {
- modal({
- title: "未登录",
- content: "请在登录后再进行操作!",
- showCancel: true,
- confirmText: "马上登录"
- }).then(res => {
- href(url)
- }).catch(() => {})
- }
- return token
- }
- const href = (url, isVerify, type = "", data = "") => {
- /*
- isVerify:是否进行登录状态校验
- type: 【默认常规跳转】close【关闭所有页面再跳转】true【覆盖当前页跳转】
- */
- if (!url) {
- url = "/"
- }
- if (data) {
- url = addUrlCode(url, data)
- }
- if (isVerify) {
- if (!isLogin(true)) {
- return false
- }
- }
- const homePages = getApp().globalData.homePages
- if (url.toLowerCase().indexOf('https://') == 0 || url.toLowerCase().indexOf('https://') == 0) {
- // #ifdef H5
- location.href = url
- // #endif
- // #ifndef H5
- toast("不支持外链")
- // #endif
- return false
- }
- if (url.startsWith('@modal')) {
- var index=url.lastIndexOf('=')
- var str=url.substring(index+1,url.length)
- modal({
- title: "提示",
- content: str,
- showCancel: false,
- confirmText: "确定"
- }).then(res => {
- }).catch(() => {})
- return false
- }
- const isHomePage = homePages.some(item => {
- return url.toLowerCase().indexOf(item.toLowerCase()) >= 0
- })
- if (isHomePage) {
- uni.switchTab({
- url: url
- })
- } else {
- if (type == 'close') {
- uni.reLaunch({
- url: url
- });
- } else if (type) {
- uni.redirectTo({
- url: url
- });
- } else {
- uni.navigateTo({
- url: url
- });
- }
- }
- }
- // 返回上一页
- const back = () => {
- const pag = prePage()
- const loginPages = getApp().globalData.loginPages
- const homePage = getApp().globalData.homePage
- if (pag) {
- let currentPage = pag.route || "";
- const isLoginPage = loginPages.some(item => {
- return currentPage.toLowerCase().indexOf(item.toLowerCase()) >= 0
- })
- if (isLoginPage) {
- uni.switchTab({
- url: homePage
- })
- } else {
- uni.navigateBack();
- }
- } else {
- uni.switchTab({
- url: homePage
- })
- }
- }
- // 查看定位位置信息
- const openLocal = (item) => {
- var latitude = parseFloat(item.lat);
- var longitude = parseFloat(item.lng);
- if (!latitude || !longitude) {
- return false
- }
- uni.openLocation({
- latitude: latitude,
- longitude: longitude,
- name: item.name || item.mapinfo,
- scale: item.scale || 18,
- success: function() {},
- fail: function(res) {}
- })
- }
- // 小程序订阅消息
- const subscribeMessage = (tmplIds) => {
- uni.requestSubscribeMessage({
- tmplIds: tmplIds,
- success(reSub) {
- if (reSub.errMsg == 'requestSubscribeMessage:ok') {
- // 订阅完成
- uni.setStorageSync('subscribeMessage', true)
- } else {
- // 订阅失败
- uni.setStorageSync('subscribeMessage', false)
- }
- }
- })
- }
- // 调取url中get参数值
- const getUrlCode = (url, name) => {
- var idx = String(url).indexOf('?') + 1
- var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
- var r = String(url).substr(idx).match(reg)
- if (r != null) return unescape(r[2])
- return null
- }
- // url中增加(替换)get参数值
- const addUrlCode = (url, data) => {
- if (!data || Object.keys(data).length <= 0) {
- return url
- }
- Object.keys(data).forEach((k, i) => {
- url = removeUrlCode(url, k)
- })
- var idx = String(url).indexOf('?')
- var len = String(url).length - 1
- if (idx < 0) {
- url += "?"
- } else if (idx < len) {
- url += "&"
- }
- Object.keys(data).forEach((k, i) => {
- url += i > 0 ? "&" : ""
- url += `${k}=${data[k]}`
- })
- return url
- }
- // 删除url中get参数值
- const removeUrlCode = (url, key) => {
- var idx = String(url).indexOf('?') + 1
- var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
- var r = String(url).substr(idx).match(reg)
- if (r != null) {
- if (r[3] && r[1]) {
- url = url.replace(r[0], r[3])
- } else {
- url = url.replace(r[0], "")
- }
- }
- return url
- }
- const isAndroid = () => {
- const res = uni.getSystemInfoSync();
- return res.platform.toLocaleLowerCase() == "android"
- }
- const isPhoneX = () => {
- const res = uni.getSystemInfoSync();
- let iphonex = false;
- let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
- const model = res.model.replace(/\s/g, "").toLowerCase()
- if (models.includes(model)) {
- iphonex = true;
- }
- return iphonex;
- }
- const getTxtKey = (str) => {
- var reg_g = /\{\{(.+?)\}\}/g
- var reg = /\{\{(\S*)\}\}/
- // var reg_g = new RegExp('{{(.+?)}}', 'g')
- // var reg = new RegExp('{{(S*)}}')
- // var val = String(str)
- const regLabel = str ? str.match(reg_g) : ''
- if (regLabel && regLabel.length > 0) {
- return regLabel.map(item => {
- const obj = reg.exec(String(item))
- return {
- key: obj[1],
- txt: obj[0]
- }
- // console.log(item, k)
- })
- }
- return []
- }
- /**
- * 获取对象下的数据,深度查询
- * @param {Any} data 查询数据
- * @param {String} _key 属性路径
- */
- const getDataAttr = (data, _key, deVal = "") => {
- var aKey = []
- if (!_key) {
- return data
- }
- if (!isArray(_key)) {
- aKey = String(_key).split(".")
- } else {
- aKey = _key
- }
- var key = aKey[0]
- var attr = deVal
- if (isArray(data)) {
- if (data.hasOwnProperty(key)) {
- if (aKey.length > 1) {
- aKey.shift()
- attr = getDataAttr(data[key], aKey)
- } else {
- attr = data[key]
- }
- }
- } else if (isObject(data)) {
- if (data.hasOwnProperty(key)) {
- if (aKey.length > 1) {
- aKey.shift()
- attr = getDataAttr(data[key], aKey)
- } else {
- attr = data[key]
- }
- }
- } else {
- return deVal
- }
- return attr
- }
- /**
- * 生成指定长度的随机字符串
- * @param {Number} min 最小程度
- * @param {Number} max 最大长度
- * @return {String} 返回生成的字符串
- */
- const randomString = (min, max) => {
- let returnStr = "",
- range = (max ? Math.round(Math.random() * (max - min)) + min : min),
- arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l',
- 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
- 'H', 'I',
- 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
- ];
- for (let i = 0; i < range; i++) {
- let index = Math.round(Math.random() * (arr.length - 1));
- returnStr += arr[index];
- }
- return returnStr;
- }
- /**
- * 精确判断数据是否是 Object 类型
- * @param {Any} val 要判断的数据
- * @returns {Boolean} true:是;false:不是;
- */
- const isObject = (val) => {
- return Object.prototype.toString.call(val) === '[object Object]' && val !== null && val !== undefined;
- }
- /**
- * 判断数据是否是 Array 类型
- * @param {Any} val 要判断的数据
- * @returns {Boolean} true:是;false:不是;
- */
- const isArray = (val) => {
- return Object.prototype.toString.call(val) === '[object Array]';
- }
- /**
- * 判断数据是否是 String 类型
- * @param {Any} val 要判断的数据
- * @returns {Boolean} true:是;false:不是;
- */
- const isString = (val) => {
- return Object.prototype.toString.call(val) === '[object String]';
- }
- /**
- * 精确判断数据是否是 Date 类型
- * @param {Any} val 要判断的数据
- * @returns {Boolean} true:是;false:不是;
- */
- const isDate = (val) => {
- return Object.prototype.toString.call(val) === '[object Date]';
- }
- /**
- * 精确判断数据是否是 Function 类型
- * @param {Any} val 要判断的数据
- * @returns {Boolean} true:是;false:不是;
- */
- const isFunction = (val) => {
- return Object.prototype.toString.call(val) === '[object Function]';
- }
- /**
- * 精确判断数据是否是 Number 类型
- * @param {Any} val 要判断的数据
- * @returns {Boolean} true:是;false:不是;
- */
- const isNumber = (val) => {
- return Object.prototype.toString.call(val) === '[object Number]';
- }
- /**
- * 精确判断数据是否是 Boolean 类型
- * @param {Any} val 要判断的数据
- * @returns {Boolean} true:是;false:不是;
- */
- const isBoolean = (val) => {
- return Object.prototype.toString.call(val) === '[object Boolean]';
- }
- const openFile = (url) => {
- if (!url) {
- return false
- }
- uni.showLoading({
- title: "文件下载中..."
- })
- uni.downloadFile({
- url: url,
- success: function(res) {
- uni.hideLoading()
- var filePath = res.tempFilePath;
- uni.showToast({
- title: "文件已下载",
- duration: 2000,
- mask: false
- })
- uni.openDocument({
- filePath: filePath,
- showMenu: true,
- success: function(e) {
- console.log('打开文档成功');
- },
- fail: (e) => {
- console.log('打开失败', e)
- }
- });
- },
- fail: function(res) {
- uni.hideLoading()
- uni.showToast({
- title: "文件下载失败",
- duration: 2000,
- mask: false
- })
- }
- });
- }
- import * as filters from './filters.js'
- export default {
- prePage, // 上一页
- rushPrePage, // 刷新上一页
- isLogin, // 判断登录状态
- href, // 跳转链接
- back, // 返回上一页
- toast, // 提示框
- copy, // 复制
- call, // 拨打电话
- modal, // 确认提示框
- wxpay, // 微信支付
- openLocal, // 查看定位信息
- getUrlCode, // 获取url的GET参数
- addUrlCode, // url增加GET参数
- removeUrlCode, // 删除url中GET参数
- subscribeMessage, // 小程序订阅消息
- openFile,
- isAndroid,
- isPhoneX,
- randomString,
- ...filters,
- getTxtKey,
- getDataAttr,
- isObject,
- isArray,
- isString,
- isDate,
- isFunction,
- isNumber,
- isBoolean
- }
|