Commit 567eb23c by 李伟康

commit

0 parents
Showing 84 changed files with 3762 additions and 0 deletions
project.private.config.json
project.config.json
File mode changed
import {
preReleaseAppId
} from '~/config'
const target = ['ip', 'dev', 'uat', 'prod', 'preRelease']
let index = 1
/**
*
0本地
1开发
2测试
3生产
4预发布
*/
const accountInfo = wx.getAccountInfoSync()
const systemInfo = wx.getSystemInfoSync()
// console.log(systemInfo);
// console.log(accountInfo.miniProgram.envVersion)
//手动控制体验版环境的请求 true就依据下面index false就默认为2
const manual = true
const release = false
// 判断小程序环境
// develop:开发版(正常开发工具,测试时)
// trial:体验版
// release:正式版
// console.log( systemInfo.platform);
// console.log(accountInfo.miniProgram.envVersion);
// 对比一下appkey
// console.log();
if (systemInfo.platform != 'devtools') {
// 判断预发布的appid 是强制锁定为4(预发布的地址)
if (accountInfo.miniProgram.appId == preReleaseAppId) {
index = 4
} else {
switch (accountInfo.miniProgram.envVersion) {
case 'develop':
// this.globalData.url = 'http://192.168.0.252:3000/api'; //
break
case 'trial':
index = manual ? index : 2
break
case 'release':
index = release ? index : 3
break
default:
index = 3
break
}
}
}
const secretKey = {
ip: {},
dev: {
sso: {
appKey: '8b31ae1009ccb0f96130ca4bd90e3d89',
secret: '02d60f17ae714872845d2aa9d3b087e109ccb0f96130ca4b'
}
},
uat: {
sso: {
appKey: '8b31ae1009ccb0f96130ca4bd90e3d89',
secret: '02d60f17ae714872845d2aa9d3b087e109ccb0f96130ca4b'
}
},
prod: {
sso: {
appKey: '8b31ae1009ccb0f96130ca4bd90e3d89',
secret: '02d60f17ae714872845d2aa9d3b087e109ccb0f96130ca4b'
}
},
preRelease: {
sso: {
appKey: '8b31ae1009ccb0f96130ca4bd90e3d89',
secret: '02d60f17ae714872845d2aa9d3b087e109ccb0f96130ca4b'
}
}
} [target[index]]
const domain = {
// ip: 'http://192.168.2.94:8558',
// ip: 'http://192.168.2.3:8315',
ip: 'http://192.168.1.117:8315',
/**登录: 192.168.2.3:8315
商城: 192.168.2.3:8558 */
dev: 'https://scrm.dev.glsx.com.cn',
uat: 'https://scrm.test.glsx.com.cn',
preRelease: 'https://scrm.beta.glsx.com.cn',
prod: 'https://scrm.glsx.com.cn'
} [target[index]]
const djDomain = {
ip: 'https://dj.dev.glsx.com.cn',
dev: 'https://dj.dev.glsx.com.cn',
preRelease: 'https://dj.beta.glsx.com.cn',
uat: 'https://dj.test.glsx.com.cn',
prod: 'https://dj.glsx.com.cn',
} [target[index]]
const djSecretKey = {
ip: {
appKey: '48e5e13229b82c1b4e6e8c96151f0637',
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
},
dev: {
appKey: '48e5e13229b82c1b4e6e8c96151f0637',
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
},
uat: {
appKey: '48e5e13229b82c1b4e6e8c96151f0637',
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
},
preRelease: {
appKey: '48e5e13229b82c1b4e6e8c96151f0637',
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
},
prod: {
appKey: 'd7ffc3346fc9a45bccaaa35300d59022',
secret: '4bc07f8868374c49a4661d603377e3106fc9a45bccaaa353'
},
pet: {
appKey: 'd7ffc3346fc9a45bccaaa35300d59022',
secret: '4bc07f8868374c49a4661d603377e3106fc9a45bccaaa353'
}
} [target[index]]
const gscDomain = {
ip: 'http://192.168.3.145:9898',
dev: 'https://gsc-agent.dev.glsx.com.cn',
uat: 'https://gsc-agent.test.glsx.com.cn',
preRelease: 'https://gsc-agent.beta.glsx.com.cn',
prod: 'https://gsc-agent.gldijia.com.cn'
} [target[index]]
const pathEnum = {
sso: '/rop-scrm-sso/',
shopmall: '/rop-scrm-shopmall/',
coupon: '/rop-scrm-coupon/',
carlife: '/rop-scrm-carlife/',
live: '/rop-scrm-live/',
equity: '/rop-scrm-equity/',
entmicro: '/rop-scrm-entmicro/',
wechat: '/rop-scrm-wechat/',
boutiquecoupon: '/rop-scrm-boutiquecoupon/',
material: '/rop-scrm-marketing/', //素材
sop: '/rop-scrm-sop/',
customercollect: '/rop-scrm-bigdatautil/',
drac: '/rop-scrm-entmicro/',
busassistant: '/rop-scrm-busassistant/',
pad: '/rop-dj-pad/',
}
const defaultMerchantId = {
ip: '44211227',
dev: '44211227',
uat: '44210895',
prod: '44208317',
preRelease: '44211283'
} [target[index]]
const CONFIG_ENV_MAP = {
'1': 'develope',
'2': 'test',
'3': 'production',
'4': 'beta'
}
module.exports = {
index,
domain,
pathEnum,
secretKey,
defaultMerchantId,
env: CONFIG_ENV_MAP[index],
gscDomain,
djSecretKey,
djDomain
}
\ No newline at end of file \ No newline at end of file
import apiModules from './module/index'
module.exports = apiModules
\ No newline at end of file \ No newline at end of file
import http from '../request/http'
const common = 'scrm.api.carlife.common.'
module.exports = {
/**上传图片
*/
uploadImg(data) {
return http.post({
method: `${common}uploadImg`,
...data,
noSignAttr: ["file"],
});
},
/**视频上传
*/
uploadVideo(data) {
return http.post({
method: `${common}uploadVideo`,
...data,
noSignAttr: ["file"],
});
},
/**获取图片版本号 */
getImgVersion() {
return http.getMock();
},
//获取北森SSO鉴权
findBeiSenSSOToken(data) {
return http.post({
method: 'dj.pad.api.beisen.findBeiSenSSOToken',
projectName: 'pad',
...data
}, true)
},
};
\ No newline at end of file \ No newline at end of file
import wechatApi from './wechat'
import userApi from './user'
import common from './common'
module.exports = {
wechatApi,
userApi,
common,
}
\ No newline at end of file \ No newline at end of file
import http from '../request/http'
const {
appId
} = wx.getAccountInfoSync().miniProgram
let loginCount = null,
loginCache = null,
loginTimer = null
class UsersApi {
/**调用后台接口获取用户信息 */
async login() {
const appEnter = wx.getEnterOptionsSync()
try {
if (appEnter.scene === 1154 && appEnter.mode === 'singlePage') throw 'login:fail rejected due to no permission currently'
if (!loginCount) {
loginCache = null
loginCount = Date.now()
const {
code
} = await this.getWxCode(),
data = await http.fetch('scrm.api.sso.weapp.jscode.login', {
appId,
code,
delSessionId: true
})
loginCache = data
loginCount = null
return Promise.resolve(data)
} else {
return new Promise((resolve) => {
loginTimer = setInterval(() => {
if (loginCache) {
clearInterval(loginTimer)
loginCount = null
resolve(loginCache)
}
}, 1e3)
})
}
} catch (error) {
if (loginTimer) clearInterval(loginTimer)
loginCount = null
return Promise.reject(error)
}
}
/**调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)、微信开放平台帐号下的唯一标识(unionid,若当前小程序已绑定到微信开放平台帐号)及本次登录的会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。 */
getWxCode() {
return new Promise((resolve, reject) => {
wx.login({
success: res => resolve(res),
fail: err => reject(err)
})
})
}
/**调用后台接口获取用户信息js_code换取sessionId */
async wxCodeLogin() {
const appEnter = wx.getEnterOptionsSync()
try {
if (appEnter.scene === 1154 && appEnter.mode === 'singlePage') throw 'login:fail rejected due to no permission currently'
const {
code
} = await this.getWxCode()
return await http.fetch('scrm.api.sso.wechat.applets.jscode.login', {
appId,
code
})
} catch (error) {
return Promise.reject(error)
}
}
/** 手机号授权解析(单纯解析内容返回前端)
* 只传loginToken就返回unionId和openid
* 传加密信息就解析手机号
*/
async getUserProfile(loginToken, detail = {}) {
if (detail.errMsg && detail.errMsg == 'getPhoneNumber:fail user deny') Promise.reject()
delete detail.errMsg
if (!loginToken) {
let res = await this.wxCodeLogin()
loginToken = res.data
}
detail.loginToken = loginToken
return http.post({
method: 'scrm.api.sso.wechat.applets.phone.grant.analysis',
...detail,
platformEntrance: 'BUSINESS_ASSISTANT'
}, true)
}
/**授权手机号 */
async authUserPhone(detail, sessionId) {
if (!sessionId) {
wx.p.wxApi.showToast('缺少sessionId')
Promise.reject({
errMsg: '缺少sessionId'
})
}
if (detail.errMsg && detail.errMsg == 'getPhoneNumber:fail user deny') Promise.reject()
delete detail.errMsg
if (detail.iv && detail.encryptedData) {
wx.p.wxApi.showLoading()
detail.sessionId = sessionId
return http.fetch('scrm.api.sso.weapp.auth.phone', detail)
} else Promise.reject(detail.errMsg)
}
/**退出登录 */
logout() {
return http.fetch('scrm.api.sso.user.logout')
}
/** 手机号获取短信验证码 */
getSmsCode(mobile) {
return http.fetch('scrm.api.sso.wechat.applets.sms.get.code', {
mobile
})
}
/** 手机号短信验证码登录 */
phoneSmsLogin(data = {}) {
return http.fetch('scrm.api.sso.wechat.applets.sms.login', {
...data,
source: 'MINIAPP',
platformEntrance: 'BUSINESS_ASSISTANT'
})
}
/*
*C端手机号短信登录
*/
phoneLogin(data) {
return http.fetch('scrm.api.sso.weapp.auth.phone.mini', {
source: 'MINIAPP',
...data
})
}
/**
* 北森登录
*/
async beisenLogin(loginToken, detail = {}) {
if (detail.errMsg && detail.errMsg == 'getPhoneNumber:fail user deny') Promise.reject()
delete detail.errMsg
if (!loginToken) {
let res = await this.wxCodeLogin()
loginToken = res.data
}
detail.loginToken = loginToken
return http.post({
method: 'scrm.api.sso.beisen.token.get',
...detail,
}, true)
}
/**
* 通过手机号获取北森token
*
*/
getBeisenToken(data){
return http.fetch('scrm.api.sso.beisen.token.by.phone', data)
}
}
export default new UsersApi()
\ No newline at end of file \ No newline at end of file
import http from '../request/http'
const path = 'scrm.api.wechat.'
module.exports = {
/** 解析scene */
getSceneById(data) {
// return api.post({
// method: `${path}get.scene.by.id`,
// ...data
// }, true)
return http.fetch(`${path}get.scene.by.id`,data);
}
}
import sign from './sign.js'
import {
defaultMerchantId,
secretKey,
pathEnum,
domain,
gscDomain,
djDomain,
djSecretKey
} from '../env/index'
const HOST = {
scrm: domain,
dj: djDomain
}
/**接口 */
class Request {
get(params, returnAll = false, hostType = 'scrm') {
return this.request('GET', params, returnAll, hostType)
}
post(params, returnAll = false, hostType = 'scrm') {
return this.request('POST', params, returnAll, hostType)
}
fetch(method, data, returnAll = true, hostType = 'scrm') {
return this.post({
method,
...data,
},
returnAll,
hostType
);
}
wx_request({
url,
method = 'GET',
data = {},
header = {},
dataType = 'json',
responseType = "text"
}) {
return new Promise((resolve) => {
wx.request({
url,
data,
method,
header,
dataType,
responseType,
success(response) {
resolve(response.data)
}
})
})
}
reportTrack(params) {
return this.request('POST', params, true)
}
request(RequestMethods, params, returnAll , hostType = 'scrm') {
return new Promise((resolve, reject) => {
wx.showNavigationBarLoading()
let header = RequestMethods === 'POST' ? {
'content-type': 'application/x-www-form-urlencoded'
} : {
'Cache-Control': 'no-cache'
}
let {
merchantId
} = wx.p.storage.get('merchant_info')
header.merchantId = wx.$merchant_id || merchantId || defaultMerchantId
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
const path = pathEnum[projectName]
params = this.getData(params, hostType)
wx.request({
url: `${HOST[hostType]}${path}router?method=${params.method}`,
data: params,
method: RequestMethods,
header,
dataType: 'json',
responseType: 'text',
success(response) {
/**业务代码 */
let {
data: {
code,
message
},
data
} = response
if (returnAll) {
resolve(data)
return
}
if (code == 20 || code == 21) {
wx.hideLoading()
const thisPage = wx.p.router.getPageInstance(),
options = Object.keys(thisPage.options)
let currentRoute = thisPage.route,
query = []
if (options.length) {
options.map(key => {
query.push(`${key}=${thisPage.options[key]}`)
})
}
if (query.length) currentRoute += `?${query.join('&')}`
return wx.p.router.redirectTo('/pages/loading/loading', {
url: `/${currentRoute}`
})
} else {
if (code == '0') {
resolve(data.data)
} else {
wx.showToast({
title: message || '系统异常',
icon: 'none'
})
}
}
},
fail(error) {
wx.hideLoading()
console.error(`接口异常:`, error)
wx.showToast({
title: typeof error == 'string' ? error : JSON.stringify(error) || '系统异常',
icon: 'error'
})
reject(error)
},
complete() {
wx.stopPullDownRefresh()
wx.hideNavigationBarLoading()
}
})
})
}
getData(params,hostType) {
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
else delete params.projectName
let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
if (secretKey[projectName]) {
appKey = secretKey[projectName].appKey
secret = secretKey[projectName].secret
}
if(hostType == 'dj'){
appKey = djSecretKey.appKey
secret = djSecretKey.secret
}
let {
sessionId
} = wx.p.storage.get()
let noSignAttr = []
if (!params.sessionId && sessionId) params.sessionId = sessionId
if (params.delSessionId) {
delete params.sessionId
delete params.delSessionId
}
if (params.noSignAttr) {
noSignAttr = params.noSignAttr
delete params.noSignAttr
}
params.v = '1.0.0'
params.format = 'json'
params.locale = 'zh_CN'
params.source = 'dj-wechat'
params.appKey = appKey
return sign(params, secret, noSignAttr)
}
getRopProject(method) {
const projectName = method.split('.')[2]
return projectName
}
gscGet(url, data = {}, returnAll = false) {
return this.gscRequest(url, params, 'GET', returnAll)
}
gscPost(url, data = {}, returnAll = false) {
return this.gscRequest(url, data, 'POST', returnAll)
}
gscRequest(url, data = {}, method = 'GET', returnAll) {
return new Promise((resolve, reject) => {
wx.showNavigationBarLoading()
wx.request({
url: `${gscDomain}/gsc-agent-manage-biz/${url}`,
data,
method,
success(response) {
let {
data
} = response
if (returnAll) {
resolve(data)
return
}
resolve(data.data)
},
fail(error) {
wx.hideLoading()
reject(error)
},
complete() {
wx.stopPullDownRefresh()
wx.hideNavigationBarLoading()
}
})
})
}
}
export default new Request()
\ No newline at end of file \ No newline at end of file
import {sha1,qs} from '../../lib/index'
const sign = (params, secret, noSignAttr = []) => {
delete params.sign
var objStr = qs.stringify(params, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
})
var objVal = objStr.split('&')
var realObj = {}
objVal.forEach(item => {
const idx = item.indexOf('=')
realObj[item.split('=')[0]] = decodeURIComponent(item.slice(idx + 1))
})
const keys = Object.keys(realObj).sort()
var str = []
var obj = null
for (const key in realObj) {
obj = realObj[key]
if (obj === null) {
obj = ''
} else if (typeof obj === 'object') {
obj = JSON.stringify(obj)
}
realObj[key] = obj
}
keys.forEach(e => {
!noSignAttr.includes(e) && str.push(e + realObj[e])
})
realObj.sign = sha1(secret + str.join('') + secret).toUpperCase()
return realObj
}
export default sign
\ No newline at end of file \ No newline at end of file
// app.js
// 初始化sentry
import sentryInit from "~/utils/sentryConfig/sentryInit";
sentryInit();
import api from "./api/index";
import { router } from "./router/index";
// 判断小程序是否需要更新
import { getUpdateManager } from "./lib/index";
import utils from "./utils/index";
// 埋点 有需要再引入
// import './utils/track/Track'
/**分享 */
import '~/utils/share'
App({
onLaunch(options) {
getUpdateManager();
/**挂载到wx对象 */
wx.p = {
authStatus: false,
...utils,
api,
router,
storage: new utils.cache.Storage(),
};
// 存储设备信息
utils.cache.storageApi.setSystem_info();
},
/**页面不存在时触发 */
onPageNotFound(e) {
wx.p.router.goHome();
},
onHide() {},
globalData: {
ROUTE_QUERY: {},
},
});
{
"pages": [
"pages/loading/loading",
"pages/login/login",
"pages/webView/webView",
"pages/noAccess/noAccess"
],
"requiredPrivateInfos": [],
"lazyCodeLoading": "requiredComponents",
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTextStyle": "black",
"navigationBarTitleText": "广联数科EHR系统"
},
"subPackages": [
{
"root": "packageIndex",
"pages": [
"pages/index/index"
]
}
],
"usingComponents": {
"navigation-bar": "/components/NavigationBar/NavigationBar"
},
"style": "v2",
"resolveAlias": {
"~/*": "/*"
},
"sitemapLocation": "sitemap.json",
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
}
}
\ No newline at end of file \ No newline at end of file
@import "assets/style/common.wxss";
page {
background-color: #F9F7F7 !important;
color: #282829;
font-size: 28rpx;
--themeColor: #14c2c3;
--btnColor: #14c2c3;
--fontColor:#23b7bb;
--borderRadius: 8rpx;
--margin: 32rpx;
/* 兼容 IOS<11.2 先constant再env */
--constantSafeAreaInsetBottom: constant(safe-area-inset-bottom);
/* 兼容 IOS>11.2 */
--envSafeAreaInsetBottom: env(safe-area-inset-bottom);
}
image {
width: 100%;
height: 100%;
vertical-align: top;
}
.flex_sc {
display: flex;
align-items: center;
}
.flex_cc {
display: flex;
align-items: center;
justify-content: center;
}
.flex_scb {
display: flex;
align-items: center;
justify-content: space-between;
}
\ No newline at end of file \ No newline at end of file
/**app.wxss**/
.flex {
display: flex;
align-items: center;
}
.sticky {
position: sticky;
top: 0;
left: 0;
z-index: 2;
background-color: #fff;
}
.flex-center {
display: flex;
align-items: center;
justify-content: start;
}
.y-center {
top: 50%;
transform: translateY(-50%);
}
.x-center {
left: 50%;
transform: translateX(-50%);
}
.box-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.text-hide {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.text-two-line {
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
}
.text-center {
display: flex;
align-items: center;
justify-content: center;
}
.isFullSucreen {
/* padding-bottom: 34px !important; */
padding-bottom: constant(safe-area-inset-bottom) !important;
padding-bottom: env(safe-area-inset-bottom) !important;
}
.isFullSucreen-bottom {
bottom: constant(safe-area-inset-bottom) !important;
bottom: env(safe-area-inset-bottom) !important;
}
.default-btn {
width: 622rpx;
height: 104rpx;
background: var(--btnColor);
border-radius: var(--borderRadius);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: var(--margin);
}
.list-nothing {
width: 100%;
padding: 8rpx 0 30rpx;
text-align: center;
font-size: 28rpx;
color: #C1C2C3;
}
.list-nothing .icon {
width: 320rpx;
height: 320rpx;
}
.list-not {
display: flex;
align-items: center;
justify-content: center;
color: #999;
font-size: 24rpx;
height: 100%;
}
@keyframes show-box {
0% {
opacity: 0;
transform: scale(2.5);
}
100% {
opacity: 1;
transform: scale(1);
}
}
@keyframes show-box-opacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes show-box-inset{
0% {
opacity: 0;
transform: scale(.1);
}
100% {
opacity: 1;
transform: scale(1);
}
}
.safe-area {
display: block;
width: 100%;
height: 0;
opacity: 0;
}
\ No newline at end of file \ No newline at end of file
// components/Modal/Modal.js
Component({
/**
* 组件的属性列表
*/
properties: {
show: Boolean,
cancelText: {
type: String,
value: '不同意'
},
confirmText: {
type: String,
value: '同意'
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
cancel() {
this.setData({
show: false
})
this.triggerEvent('cancel')
},
getPhoneNumber(e) {
this.setData({
show: false
})
this.triggerEvent('confirm', e.detail)
}
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
/* components/Modal/Modal.wxss */
.popup {
position: fixed;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
z-index: 998;
&-bg {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: #00000080;
}
.modal-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 622rpx;
min-height: 404rpx;
border-radius: 20rpx;
background: #ffffff;
display: flex;
flex-direction: column;
.footer-box {
height: 144rpx;
margin-top: auto;
display: flex;
align-items: center;
justify-content: center;
gap: 0 24rpx;
.btn {
width: 251rpx;
height: 80rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 32rpx;
border-radius: 8rpx;
margin: 0 !important;
}
.cancel {
background: #f4f6f7;
color: #222222;
}
.confirm {
background: var(--themeColor);
color: #fff;
}
}
}
}
\ No newline at end of file \ No newline at end of file
<view class="popup" wx:if="{{show}}">
<view class="popup-bg"></view>
<view class="modal-box box-center">
<slot></slot>
<view class="footer-box">
<view class="cancel btn" bind:tap="cancel">{{cancelText}}</view>
<button open-type="getPhoneNumber" catchgetphonenumber="getPhoneNumber" class="confirm btn">{{confirmText}}</button>
</view>
</view>
</view>
\ No newline at end of file \ No newline at end of file
// components/navigationBar/navigationBar.js
Component({
/**
* 组件的属性列表
*/
properties: {
navStyle: String,
custom: Boolean,
showBack: Boolean,
pageTitle: {
type: String,
value: '',
observer(n) {
if (n) {
this.title = n
this.setPageTitle()
}
}
}
},
title: '',
/**
* 组件的初始数据
*/
data: {},
/**
* 组件的方法列表
*/
methods: {
setPageTitle() {
let thisPage = wx.p.router.getPageInstance()
if (thisPage) thisPage.navigationBarTitleText = this.title
},
init() {
/**
* 获取自定义导航栏信息
*/
wx.getSystemInfo().then(res => {
let {
fontSizeSetting,
statusBarHeight,
screenWidth
} = res
const {
height,
right,
width,
top
} = wx.getMenuButtonBoundingClientRect(),
currentPages = getCurrentPages(), {
showBack
} = this.data
if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true
})
let navigationBarHeight = height + ((top - statusBarHeight) * 2)
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width * 2)
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
})
},
emit({
navigationBarHeight,
statusBarHeight
}) {
let navHeight = navigationBarHeight + statusBarHeight
const thisPage = wx.p.router.getPageInstance()
this.triggerEvent('navbarReady', {
height: navHeight,
statusBarHeight
})
this.setData({
showNavBar: true
})
thisPage.setData({
navHeight,
statusBarHeight
})
},
back() {
wx.p.router.back()
}
},
lifetimes: {
attached() {
this.init()
this.setPageTitle()
}
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class="navigation-bar" id="navigation-bar" style="padding-top:{{statusBarHeight}}px;height:{{navigationBarHeight}}px;{{navStyle}}">
<block wx:if="{{!custom}}">
<view class="navigation-bar-box" wx:if="{{showNavBar}}" style="{{navigationBarStyle}}">
<block wx:if="{{SHOWBACK}}">
<view class="back " bindtap="back">
<image class="img" src="./images/icon-back.png" />
</view>
</block>
<view class="navigation-bar-titleText" style="{{navigationBarTextWidth}}">
<slot/>
</view>
</view>
</block>
<block wx:else>
<slot/>
</block>
</view>
\ No newline at end of file \ No newline at end of file
/* components/navigationBar/navigationBar.wxss */
.navigation-bar {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 99;
background-color: #FFFFFF;
transition: all .15s;
}
.navigation-bar-box {
position: relative;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.navigation-bar-titleText {
color: #333333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 500;
box-sizing: border-box;
text-align: center;
letter-spacing: 1rpx;
}
.back-box {
width: 76rpx;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
.back {
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 100rpx;
/* height: 34rpx; */
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.back .img {
width: 16rpx;
height: 34rpx;
}
\ No newline at end of file \ No newline at end of file
/**
* 用来配置小程序项目的变量
* 统一管理
*/
// 配置预发布的小程序aapId
export const preReleaseAppId = 'wx6e40cfb83ce4ffb1'
// sentry Dsn 地址
export const dsnUrl = 'https://44b18e4acc2e4ab18f12a69a561b55bc@sentry.glsx.com.cn/39'
// cdn图片地址
export const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/miniprogram/hmd/'
import sha1 from './sha1.js'
import qs from './qs'
import wxqrcode from './wxqrcode.js'
import getUpdateManager from "./wxUpdateManager";
import * as Sentry from './sentry-miniapp'
module.exports ={ sha1,qs,wxqrcode,getUpdateManager,Sentry }
\ No newline at end of file \ No newline at end of file
This diff is collapsed. Click to expand it.
var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var S=_((le,M)=>{"use strict";M.exports=N;function y(t){return t instanceof Buffer?Buffer.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function N(t){if(t=t||{},t.circles)return Q(t);return t.proto?s:a;function e(f,i){for(var r=Object.keys(f),n=new Array(r.length),u=0;u<r.length;u++){var o=r[u],p=f[o];typeof p!="object"||p===null?n[o]=p:p instanceof Date?n[o]=new Date(p):ArrayBuffer.isView(p)?n[o]=y(p):n[o]=i(p)}return n}function a(f){if(typeof f!="object"||f===null)return f;if(f instanceof Date)return new Date(f);if(Array.isArray(f))return e(f,a);if(f instanceof Map)return new Map(e(Array.from(f),a));if(f instanceof Set)return new Set(e(Array.from(f),a));var i={};for(var r in f)if(Object.hasOwnProperty.call(f,r)!==!1){var n=f[r];typeof n!="object"||n===null?i[r]=n:n instanceof Date?i[r]=new Date(n):n instanceof Map?i[r]=new Map(e(Array.from(n),a)):n instanceof Set?i[r]=new Set(e(Array.from(n),a)):ArrayBuffer.isView(n)?i[r]=y(n):i[r]=a(n)}return i}function s(f){if(typeof f!="object"||f===null)return f;if(f instanceof Date)return new Date(f);if(Array.isArray(f))return e(f,s);if(f instanceof Map)return new Map(e(Array.from(f),s));if(f instanceof Set)return new Set(e(Array.from(f),s));var i={};for(var r in f){var n=f[r];typeof n!="object"||n===null?i[r]=n:n instanceof Date?i[r]=new Date(n):n instanceof Map?i[r]=new Map(e(Array.from(n),s)):n instanceof Set?i[r]=new Set(e(Array.from(n),s)):ArrayBuffer.isView(n)?i[r]=y(n):i[r]=s(n)}return i}}function Q(t){var e=[],a=[];return t.proto?i:f;function s(r,n){for(var u=Object.keys(r),o=new Array(u.length),p=0;p<u.length;p++){var c=u[p],l=r[c];if(typeof l!="object"||l===null)o[c]=l;else if(l instanceof Date)o[c]=new Date(l);else if(ArrayBuffer.isView(l))o[c]=y(l);else{var h=e.indexOf(l);h!==-1?o[c]=a[h]:o[c]=n(l)}}return o}function f(r){if(typeof r!="object"||r===null)return r;if(r instanceof Date)return new Date(r);if(Array.isArray(r))return s(r,f);if(r instanceof Map)return new Map(s(Array.from(r),f));if(r instanceof Set)return new Set(s(Array.from(r),f));var n={};e.push(r),a.push(n);for(var u in r)if(Object.hasOwnProperty.call(r,u)!==!1){var o=r[u];if(typeof o!="object"||o===null)n[u]=o;else if(o instanceof Date)n[u]=new Date(o);else if(o instanceof Map)n[u]=new Map(s(Array.from(o),f));else if(o instanceof Set)n[u]=new Set(s(Array.from(o),f));else if(ArrayBuffer.isView(o))n[u]=y(o);else{var p=e.indexOf(o);p!==-1?n[u]=a[p]:n[u]=f(o)}}return e.pop(),a.pop(),n}function i(r){if(typeof r!="object"||r===null)return r;if(r instanceof Date)return new Date(r);if(Array.isArray(r))return s(r,i);if(r instanceof Map)return new Map(s(Array.from(r),i));if(r instanceof Set)return new Set(s(Array.from(r),i));var n={};e.push(r),a.push(n);for(var u in r){var o=r[u];if(typeof o!="object"||o===null)n[u]=o;else if(o instanceof Date)n[u]=new Date(o);else if(o instanceof Map)n[u]=new Map(s(Array.from(o),i));else if(o instanceof Set)n[u]=new Set(s(Array.from(o),i));else if(ArrayBuffer.isView(o))n[u]=y(o);else{var p=e.indexOf(o);p!==-1?n[u]=a[p]:n[u]=i(o)}}return e.pop(),a.pop(),n}}});var V=_((ce,I)=>{"use strict";var C=Array.isArray,W=Object.keys,Z=Object.prototype.hasOwnProperty;I.exports=function t(e,a){if(e===a)return!0;if(e&&a&&typeof e=="object"&&typeof a=="object"){var s=C(e),f=C(a),i,r,n;if(s&&f){if(r=e.length,r!=a.length)return!1;for(i=r;i--!=0;)if(!t(e[i],a[i]))return!1;return!0}if(s!=f)return!1;var u=e instanceof Date,o=a instanceof Date;if(u!=o)return!1;if(u&&o)return e.getTime()==a.getTime();var p=e instanceof RegExp,c=a instanceof RegExp;if(p!=c)return!1;if(p&&c)return e.toString()==a.toString();var l=W(e);if(r=l.length,r!==W(a).length)return!1;for(i=r;i--!=0;)if(!Z.call(a,l[i]))return!1;for(i=r;i--!=0;)if(n=l[i],!t(e[n],a[n]))return!1;return!0}return e!==e&&a!==a}});var q=_(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0}),A.parseMultiDataPaths=ee,A.getDataOnPath=void 0;var E=/^\s/,b=function(t,e){throw new Error('Parsing data path "'+t+'" failed at char "'+t[e]+'" (index '+e+")")},L=function(t,e){for(var a=e.index;e.index<e.length;){var s=t[e.index];if(/^[0-9]/.test(s)){e.index++;continue}break}return a===e.index&&b(t,e.index),parseInt(t.slice(a,e.index),10)},R=function(t,e){var a=e.index,s=t[a];if(/^[_a-zA-Z$]/.test(s))for(e.index++;e.index<e.length;){var f=t[e.index];if(/^[_a-zA-Z0-9$]/.test(f)){e.index++;continue}break}else b(t,e.index);return t.slice(a,e.index)},B=function(t,e){for(var a=[R(t,e)],s={deepCmp:!1};e.index<e.length;){var f=t[e.index];if(f==="[")e.index++,a.push(L(t,e)),t[e.index]!=="]"&&b(t,e.index),e.index++;else if(f==="."){if(e.index++,t[e.index]==="*"){if(e.index++,t[e.index]==="*"){e.index++,s.deepCmp=!0;break}b(t,e.index)}a.push(R(t,e))}else break}return{path:a,options:s}},X=function(t,e){for(;E.test(t[e.index]);)e.index++;for(var a=[B(t,e)],s=!1;e.index<e.length;){var f=t[e.index];E.test(f)?e.index++:f===","?(s=!0,e.index++):s?(s=!1,a.push(B(t,e))):b(t,e.index)}return a},k=function(t,e){e.index<e.length&&b(t,e.index)};function ee(t){var e={length:t.length,index:0},a=X(t,e);return k(t,e),a}var te=function(t,e){var a=t;return e.forEach(function(s){a=typeof a!="object"||a===null?void 0:a[s]}),a};A.getDataOnPath=te});var H=_(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0}),m.create=re,m.unwrap=ne;var z=function(t,e,a){if(typeof t!="object"||t===null)return t;var s={get:function(f,i){if(i==="__rawObject__")return t;var r=a.concat(i),n=t[i];return e.push({path:r,value:n}),z(n,e,r)}};return new Proxy(t,s)};function re(t,e){return z(t,e,[])}function ne(t){return typeof t!="object"||t===null||typeof t.__rawObject__!="object"?t:t.__rawObject__}});var K=_(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0}),x.behavior=void 0;var $,ae=G(S()),ie=G(V()),w=U(q()),j=U(H());function F(t,e,a){return e in t?Object.defineProperty(t,e,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[e]=a,t}function G(t){return t&&t.__esModule?t:{default:t}}function U(t){if(t&&t.__esModule)return t;var e={};if(t!=null){for(var a in t)if(Object.prototype.hasOwnProperty.call(t,a)){var s=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(t,a):{};s.get||s.set?Object.defineProperty(e,a,s):e[a]=t[a]}}return e.default=t,e}var T=ae.default({proto:!0}),fe=0,oe=Behavior({lifetimes:{attached:function(){this.setData({_computedWatchInit:"attached"})},created:function(){this.setData({_computedWatchInit:"created"})}},definitionFilter:function(t){var e=t.computed,a=t.watch,s=[],f=fe++;s.push({fields:"_computedWatchInit",observer:function(){var i=this.data._computedWatchInit;if(i==="created"){var r={computedUpdaters:[],computedRelatedPathValues:{},watchCurVal:{}};this._computedWatchInfo||(this._computedWatchInfo={}),this._computedWatchInfo[f]=r,a&&Object.keys(a).forEach(function(u){var o=w.parseMultiDataPaths(u).map(function(p){var c=p.path,l=p.options,h=w.getDataOnPath(this.data,c);return l.deepCmp?T(h):h}.bind(this));r.watchCurVal[u]=o}.bind(this))}else if(i==="attached"){var n=this._computedWatchInfo[f];e&&Object.keys(e).forEach(function(u){var o=e[u],p=[],c=o(j.create(this.data,p)),l=p.map(function(d){var v=d.path;return{path:v,value:w.getDataOnPath(this.data,v)}}.bind(this));this.setData(F({},u,j.unwrap(c))),n.computedRelatedPathValues[u]=l;var h=function(){for(var d=n.computedRelatedPathValues[u],v=!1,D=0;D<d.length;D++){var P=d[D],Y=P.path;if(P.value!==w.getDataOnPath(this.data,Y)){v=!0;break}}if(!v)return!1;var g=[],J=o(j.create(this.data,g));return this.setData(F({},u,j.unwrap(J))),n.computedRelatedPathValues[u]=g,!0}.bind(this);n.computedUpdaters.push(h)}.bind(this))}}}),e&&s.push({fields:"**",observer:function(){if(this._computedWatchInfo){var i,r=this._computedWatchInfo[f];if(r)do i=r.computedUpdaters.some(function(n){return n.call(this)}.bind(this));while(i)}}}),a&&Object.keys(a).forEach(function(i){var r=w.parseMultiDataPaths(i);s.push({fields:i,observer:function(){if(this._computedWatchInfo){var n=this._computedWatchInfo[f];if(n){var u=n.watchCurVal[i],o=r.map(function(h){var d=h.path,v=h.options;return{val:w.getDataOnPath(this.data,d),options:v}}.bind(this)),p=o.map(function(h){var d=h.val;return h.options.deepCmp?T(d):d});n.watchCurVal[i]=p;for(var c=!1,l=0;l<p.length;l++)if(r[l].options.deepCmp?!ie.default(u[l],p[l]):u[l]!==p[l]){c=!0;break}c&&a[i].apply(this,o.map(function(h){return h.val}))}}}})}),typeof t.observers!="object"&&(t.observers={}),Array.isArray(t.observers)?($=t.observers).push.apply($,s):s.forEach(function(i){var r=t.observers[i.fields];r?t.observers[i.fields]=function(){i.observer.call(this),r.call(this)}:t.observers[i.fields]=i.observer})}});x.behavior=oe});"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"behavior",{enumerable:!0,get:function(){return O.behavior}}),exports.ComponentWithComputed=se,exports.BehaviorWithComputed=ue;var O=K();function se(t){return Array.isArray(t.behaviors)||(t.behaviors=[]),t.behaviors.unshift(O.behavior),Component(t)}function ue(t){return Array.isArray(t.behaviors)||(t.behaviors=[]),t.behaviors.unshift(O.behavior),Behavior(t)}
This diff is collapsed. Click to expand it.
function encodeUTF8(s) {
var i, r = [], c, x;
for (i = 0; i < s.length; i++)
if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
else {
if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
else r.push(0xE0 + (c >> 12 & 0xF));
r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
};
return r;
}
// 字符串加密成 hex 字符串
function sha1(s) {
var data = new Uint8Array(encodeUTF8(s))
var i, j, t;
var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
s[l - 1] = data.length << 3;
var w = [], f = [
function () { return m[1] & m[2] | ~m[1] & m[3]; },
function () { return m[1] ^ m[2] ^ m[3]; },
function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
function () { return m[1] ^ m[2] ^ m[3]; }
], rol = function (n, c) { return n << c | n >>> (32 - c); },
k = [1518500249, 1859775393, -1894007588, -899497514],
m = [1732584193, -271733879, null, null, -1009589776];
m[2] = ~m[0], m[3] = ~m[1];
for (i = 0; i < s.length; i += 16) {
var o = m.slice(0);
for (j = 0; j < 80; j++)
w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
};
t = new DataView(new Uint32Array(m).buffer);
for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);
var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
return (e < 16 ? "0" : "") + e.toString(16);
}).join("");
return hex;
}
module.exports = sha1
function e(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,a)}return o}function t(t){for(var a=1;a<arguments.length;a++){var r=null!=arguments[a]?arguments[a]:{};a%2?e(Object(r),!0).forEach((function(e){o(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):e(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function o(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}var a=["canvasGetImageData","canvasPutImageData","canvasToTempFilePath","setEnableDebug","startAccelerometer","stopAccelerometer","getBatteryInfo","getClipboardData","setClipboardData","startCompass","stopCompass","addPhoneContact","startGyroscope","stopGyroscope","startBeaconDiscovery","stopBeaconDiscovery","getBeacons","startLocalServiceDiscovery","stopLocalServiceDiscovery","startDeviceMotionListening","stopDeviceMotionListening","getNetworkType","makePhoneCall","scanCode","getSystemInfo","vibrateShort","vibrateLong","getExtConfig","chooseLocation","getLocation","openLocation","chooseMessageFile","loadFontFace","chooseImage","previewImage","getImageInfo","saveImageToPhotosAlbum","compressImage","chooseVideo","saveVideoToPhotosAlbum","downloadFile","request","connectSocket","closeSocket","sendSocketMessage","uploadFile","login","checkSession","chooseAddress","authorize","addCard","openCard","chooseInvoice","chooseInvoiceTitle","getUserInfo","requestPayment","getWeRunData","showModal","showToast","hideToast","showLoading","hideLoading","showActionSheet","pageScrollTo","startPullDownRefresh","stopPullDownRefresh","setBackgroundColor","setBackgroundTextStyle","setTabBarBadge","removeTabBarBadge","showTabBarRedDot","hideTabBarRedDot","showTabBar","hideTabBar","setTabBarStyle","setTabBarItem","setTopBarText","saveFile","openDocument","getSavedFileList","getSavedFileInfo","removeSavedFile","getFileInfo","getStorage","setStorage","removeStorage","clearStorage","getStorageInfo","closeBLEConnection","closeBluetoothAdapter","createBLEConnection","getBLEDeviceCharacteristics","getBLEDeviceServices","getBluetoothAdapterState","getBluetoothDevices","getConnectedBluetoothDevices","notifyBLECharacteristicValueChange","openBluetoothAdapter","readBLECharacteristicValue","startBluetoothDevicesDiscovery","stopBluetoothDevicesDiscovery","writeBLECharacteristicValue","getHCEState","sendHCEMessage","startHCE","stopHCE","getScreenBrightness","setKeepScreenOn","setScreenBrightness","connectWifi","getConnectedWifi","getWifiList","setWifiList","startWifi","stopWifi","getBackgroundAudioPlayerState","playBackgroundAudio","pauseBackgroundAudio","seekBackgroundAudio","stopBackgroundAudio","getAvailableAudioSources","startRecord","stopRecord","setInnerAudioOption","playVoice","pauseVoice","stopVoice","getSetting","openSetting","getShareInfo","hideShareMenu","showShareMenu","updateShareMenu","checkIsSoterEnrolledInDevice","checkIsSupportSoterAuthentication","startSoterAuthentication","navigateBackMiniProgram","navigateToMiniProgram","setNavigationBarTitle","showNavigationBarLoading","hideNavigationBarLoading","setNavigationBarColor","redirectTo","reLaunch","navigateTo","switchTab","navigateBack"];Promise.prototype.finally||(Promise.prototype.finally=function(e){var t=this.constructor;return this.then((function(o){return t.resolve(e()).then((function(){return o}))}),(function(o){return t.resolve(e()).then((function(){throw o}))}))});var r=function(e){return function(){var o=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Promise((function(a,r){e(t({fail:r,success:a},o))}))}},n=function(){wx.pro={},Object.keys(wx).forEach((function(e){a.indexOf(e)>=0?wx.pro[e]=r(wx[e]):"createSignal"!==e&&"lanDebug"!==e&&(wx.pro[e]=wx[e])}))};export{r as promisify,n as promisifyAll};
//# sourceMappingURL=wx-promise-pro.js.map
const getUpdateManager = () => {
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
// 请求完新版本信息的回调
})
updateManager.onUpdateReady(function () {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function (res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function () {
// 新版本下载失败
})
}
export default getUpdateManager
module.exports = {
}
{
"name": "hmd",
"version": "1.0.0",
"lockfileVersion": 1
}
{
"name": "hmd",
"version": "1.0.0",
"main": "app.js",
"dependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "http://192.168.3.233:8090/saas/mini-program/hmd"
},
"author": "",
"license": "ISC",
"description": ""
}
// packageIndex/pages/index/index.js
const BeiSenIndexUrl = 'https://cloud.italent.cn/mrest/ITalentApp/iTalentMobile/100000/PageControl/RedirectUsagePage?scene=0'
Page({
/**
* 页面的初始数据
*/
data: {
indexUrl: ''
},
/**
* 生命周期函数--监听页面加载
*/
async onLoad(options) {
const returnUrl = encodeURIComponent(BeiSenIndexUrl)
if (options.beiSenToken) {
this.setData({
indexUrl: `${options.beiSenToken}&return_url=${returnUrl}`
})
} else {
const {
userInfo
} = this.data || {}
if (!userInfo.beiSenToken || !userInfo.phone) return wx.p.router.goHome()
try {
wx.p.wxApi.showLoading()
const {
code,
data,
message
} = await wx.p.api.userApi.getBeisenToken({
phone: userInfo.phone
})
wx.p.wxApi.hideLoading()
if (code == 0) {
wx.p.storage.set('userInfo', data)
this.setData({
indexUrl: `${data.beiSenToken}&return_url=${returnUrl}`
})
} else throw message
} catch (error) {
wx.p.wxApi.hideLoading()
if (error) wx.p.wxApi.showToast(String(error))
}
//
// this.setData({
// indexUrl: `}&return_url=${returnUrl}`
// })
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
wx.hideHomeButton()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
\ No newline at end of file \ No newline at end of file
{
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
/* packageIndex/pages/index/index.wxss */
\ No newline at end of file \ No newline at end of file
<web-view src="{{indexUrl}}"/>
\ No newline at end of file \ No newline at end of file
// pages/loading/loading.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
async onLoad(options) {
console.log('---------------- 页面初始化 ----------------')
console.log('options参数:', options)
this.tabList = __wxConfig?.tabBar?.list || []
wx.p.wxApi.showLoading()
//scenc获取页面参数并跳转
if (options.scene) {
return this.getSceneById(options.scene)
}
if (options.url) {
return this.login(options)
}
this.login()
},
async login(options = {}) {
try {
const userInfo = wx.p.storage.get('userInfo')
if (!userInfo.beiSenToken) wx.p.router.goHome(this.options)
else {
wx.p.wxApi.hideLoading()
wx.$LoginStatus = false
if (options.url) return this.jumpPage(options.url)
wx.p.router.reLaunch('/packageIndex/pages/index/index', this.options)
}
} catch (error) {
wx.p.wxApi.hideLoading()
wx.$LoginStatus = true //请求失败默认未登录
if (error) wx.p.wxApi.showToast(String(error))
wx.p.router.goHome(this.options)
}
},
async getSceneById(scene) {
const id = decodeURIComponent(scene).split('=').at(-1)
try {
const {
code,
data
} = await wx.p.api.wechatApi.getSceneById({
id
})
const params = data.scene.split('url='),
options = {}
if (params.length > 1) options.url = params.at(-1)
if (code == 0) this.login(options)
else throw {}
} catch (error) {
wx.p.wxApi.showToast(error || '获取scene失败')
this.login()
}
},
jumpPage(val) {
const targetPath = decodeURIComponent(val),
{
url,
events
} = this.setRouteData(targetPath),
routeName = this.tabList.findIndex(e => `/${e.pagePath}` == `${url}.html`) > -1 ? 'switchTab' : 'redirectTo'
events.notIntercept = true
wx.p.router[routeName](url, events)
},
setRouteData(targetPath) {
let [url, query] = targetPath.split('?'),
events = {}
if (query) {
let arr = query.split('&')
arr.map(e => {
let [key, val] = e.split('=')
if (val == 'false' || val == 'true') val = JSON.parse(val)
Object.assign(events, {
[key]: val
})
})
}
return {
url,
events
}
}
})
\ No newline at end of file \ No newline at end of file
{
"usingComponents": {},
"navigationStyle": "custom"
}
\ No newline at end of file \ No newline at end of file
/* pages/loading/loading.wxss */
\ No newline at end of file \ No newline at end of file
// pages/login/login.js
Page({
/**
* 页面的初始数据
*/
data: {
isAgree: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
},
async getPhoneNumber({
detail
}) {
this.setData({
isAgree: true
})
try {
const {
wxCode
} = this
if (detail.errMsg && ['authorized', 'deny'].findIndex(e => detail.errMsg.toLowerCase().includes(e)) != -1) return
if (!detail?.code) throw '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
wx.p.wxApi.showLoading()
const {
code,
data,
message
} = await wx.p.api.userApi.beisenLogin(wxCode, detail)
wx.hideLoading()
if (code == '0') {
wx.p.storage.set('userInfo', data)
if (data.beiSenToken) wx.p.router.reLaunch('/packageIndex/pages/index/index', data)
else wx.p.router.go('/pages/noAccess/noAccess', data)
} else {
this.onLoad()
throw message
}
} catch (error) {
if (error) wx.p.wxApi.showToast(String(error))
}
},
showTips() {
this.setData({
showModal: true
})
},
// 同意隐私政策
handleChangeAgree() {
this.setData({
isAgree: !this.data.isAgree
})
},
// 跳转隐私政策页面
handleAgree(e) {
const {
name
} = e.currentTarget.dataset
wx.p.router.jumpH5(`https://img02.glsx.com.cn/weapp/resource/saas/scrm/html/${name}.html`, true)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
async onShow() {
let {
options
} = this
if (options.wxCode) {
this.wxCode = wxCode
return
}
wx.p.wxApi.showLoading()
const {
data
} = await wx.p.api.userApi.wxCodeLogin()
if (data) this.wxCode = data
wx.hideLoading()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
\ No newline at end of file \ No newline at end of file
{
"usingComponents": {
"modal":"/components/Modal/Modal"
},
"navigationStyle": "custom"
}
\ No newline at end of file \ No newline at end of file
/* pages/login/login.wxss */
page {
// background-color: #FAFBFF !important;
}
.layout {
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: url('https://img02.glsx.com.cn/weapp/resource/miniprogram/shuke-hr/login-bg.webp') no-repeat;
background-size: 100% 100%;
z-index: -1;
}
.logo-box {
display: flex;
align-items: center;
flex-direction: column;
padding-top: 416rpx;
.logo {
width: 208rpx;
height: 208rpx;
background: url('https://img02.glsx.com.cn/weapp/resource/miniprogram/shuke-hr/logo.webp') no-repeat;
background-size: 100% 100%;
}
.title {
font-size: 48rpx;
font-weight: 700;
line-height: 64rpx;
color: #222222;
text-align: center;
margin-top: 40rpx;
}
}
}
.wx-box {
margin: 20vh auto 0;
}
.wx-auth-button {
width: 622rpx !important;
height: 104rpx;
background: var(--themeColor);
border-radius: 8rpx;
font-weight: 500;
font-size: 32rpx;
color: #FFFFFF;
padding: 0;
}
.wx-auth-button[disabled]:not([type]) {
background: #CCCED1 !important;
border-color: #CCCED1 !important;
color: #fff !important;
box-shadow: none;
}
.wx-auth-button[disabled]:not([type])::after {
border-color: #CCCED1 !important;
}
.tips {
font-size: 24rpx;
color: #999999;
width: 100%;
padding-top: 50rpx;
}
.tips .check {
width: 28rpx;
height: 28rpx;
box-sizing: border-box;
border-radius: 100%;
border: 2rpx solid #999999;
margin-right: 8rpx;
position: relative;
}
.tips .check.true {
border-color: var(--fontColor);
background-color: var(--fontColor);
}
.tips .check .icon {
display: none;
position: absolute;
width: 30rpx;
height: 30rpx;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.tips .check.true .icon {
display: block;
}
.txt-orange {
color: var(--fontColor);
}
.modal-content {
padding-top: 48rpx;
.modal-title {
font-size: 34rpx;
font-weight: 500;
line-height: 52rpx;
color: #222222;
text-align: center;
margin-bottom: 16rpx;
}
.modal-text {
text-align: center;
font-size: 32rpx;
font-weight: 400;
line-height: 48rpx;
color: #666666;
}
}
\ No newline at end of file \ No newline at end of file
<view class="layout">
<view class="content">
<view class="logo-box">
<view class="logo"></view>
<view class="title">
广联数科EHR系统
</view>
</view>
<view class="wx-box">
<block wx:if="{{!isAgree}}">
<button class="wx-auth-button text-center {{isAgree}}" bindtap="showTips">登录</button>
</block>
<block wx:else>
<button open-type="getPhoneNumber" catchgetphonenumber="getPhoneNumber" class="wx-auth-button text-center">登录</button>
</block>
<view class="tips text-center" bindtap="handleChangeAgree">
<view class="check {{isAgree}}">
<image src="/assets/images/check.png" class="icon" />
</view>
我已阅读并同意
<text class="txt-orange" catchtap="handleAgree" data-name="privacy">《隐私协议》</text>
<text class="txt-orange" catchtap="handleAgree" data-name="agreement">《用户协议》</text>
</view>
</view>
</view>
</view>
<modal bindconfirm="getPhoneNumber" model:show="{{showModal}}">
<view class="modal-content">
<view class="modal-title">隐私协议与用户协议</view>
<view class="modal-text">
<view class="modal-tips">为保障你的合法权益,请阅读并同意</view>
<text class="txt-orange" catchtap="handleAgree" data-name="privacy">《隐私协议》</text>
<text class="txt-orange" catchtap="handleAgree" data-name="agreement">《用户协议》</text>
</view>
</view>
</modal>
\ No newline at end of file \ No newline at end of file
// pages/noAccess/noAccess.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
if(options.phone) options.phone = options.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
this.setData({
options
})
},
back(){
wx.p.router.back()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
\ No newline at end of file \ No newline at end of file
{
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
/* pages/noAccess/noAccess.wxss */
.layout {
.content {
padding-top: 368rpx;
display: flex;
flex-direction: column;
align-items: center;
.icon {
width: 216rpx;
height: 216rpx;
background: url('https://img02.glsx.com.cn/weapp/resource/miniprogram/shuke-hr/no-access.webp') no-repeat;
background-size: 100% 100%;
margin-bottom: 32rpx;
}
.text {
font-size: 28rpx;
font-weight: 400;
line-height: 44rpx;
color: #333333;
text-align: center;
max-width: 590rpx;
}
}
.back-btn {
margin: 288rpx auto 0;
}
}
\ No newline at end of file \ No newline at end of file
<view class="layout">
<view class="content">
<view class="icon"></view>
<view class="text">
当前手机号[{{options.phone || '****'}}]未授权北森iTalent,
</view>
<view class="text">无法登录,请联系人事或重新授权登录</view>
</view>
<view class="back-btn default-btn" bindtap="back">返回登录页</view>
</view>
\ No newline at end of file \ No newline at end of file
// pages/webView/webView.js
Page({
/**
* 页面的初始数据
*/
data: {
flag: true
},
getParams(str) {
let params = str.split('?')
if (params.length < 2) return {}
let param = params[1].split('&')
let obj = {}
for (let i = 0; i < param.length; i++) {
let paramsA = param[i].split('=')
let key = paramsA[0]
let value = paramsA[1]
obj[key] = value
}
return obj
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.p.wxApi.showLoading('加载中...')
let decodeUrl = decodeURIComponent(options.url)
let param = this.getParams(decodeUrl)
if (param.urlParam) {
let query = JSON.parse(param.urlParam)
this.data.refresh = query.refresh
}
this.setData({
url: decodeUrl
})
wx.hideLoading()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
if (this.data.refresh) {
this.setData(
{
flag: true
},
() => {
this.setData({
url: this.data.url
})
}
)
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
if (this.data.refresh) {
this.setData({
flag: false
})
}
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
if (this.data.refresh) {
this.setData({
flag: false
})
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {}
})
{
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
/* pages/webView/webView.wxss */
\ No newline at end of file \ No newline at end of file
<!-- <web-view src="{{url}}"></web-view> -->
<block wx:if="{{flag}}">
<web-view src="{{url}}"></web-view>
</block>
\ No newline at end of file \ No newline at end of file
/* pages/webView/webView.wxss */
\ No newline at end of file \ No newline at end of file
import router from "./router.js";
import routerBefore from './routerBefore'
module.exports={
router,
routerBefore
}
\ No newline at end of file \ No newline at end of file
class Router {
constructor(router) {}
/**获取页面对象实例 */
getPageInstance = (size = 1) => {
const pages = getCurrentPages();
return pages[pages.length - size];
};
/**跳转至H5 */
jumpH5(url, notIntercept) {
if (notIntercept) wx.navigateTo({
url: `/pages/webView/webView?url=${encodeURIComponent(url)}`,
})
else this.intercept(url).then((response) => {
if (response) return;
wx.navigateTo({
url: `/pages/webView/webView?url=${encodeURIComponent(url)}`,
});
});
}
/**
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 ||
* 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 $router.back() 可以返回到原页面。小程序中页面栈最多十层
*/
go(route, events = {}) {
this._to(
route,
events,
'navigateTo',
(res) => events && res.eventChannel.emit('getData', events)
);
}
/**关闭所有页面,打开到应用内的某个页面 */
reLaunch(route, events = {}) {
this._to(route, events, 'reLaunch');
}
/**关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 */
redirectTo(route, events = {}) {
this._to(route, events, 'redirectTo');
}
/**
* 跳转到switchTab
*/
switchTab(route, events = {}) {
this._to(route, events, 'switchTab');
}
_to(route, events = {}, to, success) {
getApp().globalData.ROUTE_QUERY = events
if (events.notIntercept) {
wx[to]({
url: route,
success
});
} else {
this.intercept().then((result) => {
!result && wx[to]({
url: route,
success
});
});
}
}
/**prevPageSize = 1
* 返回上prevPageSize页
* callBack返回上prevPageSize页对象 */
back(callBack, prevPageSize = 1) {
let prevPage = this.getPageInstance(Number(prevPageSize) + 1);
if (callBack && 'function' === typeof callBack) callBack(prevPage);
wx.navigateBack({
delta: prevPageSize,
}).catch((err) => {
this.goHome();
});
}
goHome(options) {
this._to('/pages/login/login', options, 'reLaunch')
}
/**获取上一个页面传的数据 */
getData(callBack) {
const data = this.getPageInstance().getOpenerEventChannel();
if (Object.keys(data).length !== 0)
data.on('getData', (res) => callBack(res));
}
/**
*
* @param {*} auto 是否自动跳转到登录,默认自动跳转
* @param {*} callBack true未登录 false已登录
*/
async intercept(auto = true) {
return false;
const authStatus = wx.$LoginStatus
if (authStatus) {
if (auto) wx.navigateTo({
url: '/pages/Login/Login',
})
return true;
} else {
return false;
}
}
}
export default new Router();
\ No newline at end of file \ No newline at end of file
class RouterBefore {
constructor(options) {
console.log('---------------- 路由初始化 ----------------')
this.initPageProxy()
}
/**监听页面 */
pageLeaveProxy(thisPage) {
let onLoad = thisPage.onLoad,
onShow = thisPage.onShow
thisPage.onLoad = function () {
const event = getApp().globalData.ROUTE_QUERY
const userInfo = wx.p.storage.get('userInfo')
let options = {
...event,
...arguments[0]
}
getApp().globalData.ROUTE_QUERY = {}
this.setData({
userInfo: userInfo || {}
})
onLoad && onLoad.apply(this, [options]), (this.options = options)
}
thisPage.onShow = function () {
const userInfo = wx.p.storage.get('userInfo')
onShow && onShow.apply(this, arguments), (this.setData({
userInfo: userInfo || {}
}))
}
}
/**全局注册事件 */
initPageProxy() {
let thisPage = Page
let _this = this
Page = function (el) {
try {
el || (el = {}), _this.pageLeaveProxy(el), thisPage.apply(this, arguments)
} catch (el) {
thisPage.apply(this, arguments)
}
}
}
}
export default new RouterBefore()
\ No newline at end of file \ No newline at end of file
{
"desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
"rules": [{
"action": "allow",
"page": "*"
}]
}
\ No newline at end of file \ No newline at end of file
import Storage from './storage'
import userInfo from './userInfo'
import storageApi from './storageApi'
module.exports={Storage,userInfo,storageApi}
\ No newline at end of file \ No newline at end of file
/**
* 微信小程序标准版:统一封装的 storage 操作类
*/
import { DEFAULT_GET_STORAGEKEY, STORAGE_OBJECTkEY } from '~/utils/constants'
class Storage {
types = {
1: 'get', // get
2: 'set', // set
3: 'rm' // rm
}
envVersion = {
develop: '开发版',
trial: '体验版',
release: '正式版'
}
// defaultGetStorageKey = DEFAULT_GET_STORAGEKEY
/** 构造函数 */
constructor() {
/** 获取当前小程序环境变量 */
const accountInfo = wx.getAccountInfoSync()
this.environment = accountInfo?.miniProgram.envVersion || 'release'
}
/**
*
* @param {*} key | 要操作的键值
* @param {*} type | 类型,是 get set rm
* @param {*} emptyFlag | 是否判断为空情况,默认判断 true,false 为不判断
*/
checkKeyType(key, type, emptyFlag = true) {
if (typeof key != 'string') {
throw new Error(`Storage ${this.types[type]} func: key must be string`)
return false
}
if (emptyFlag) {
let tmpKey = key.TrimStr()
if (tmpKey == '') {
throw new Error(`Storage ${this.types[type]} func: key can not be empty`)
return false
}
// if STORAGE_OBJECTkEY[key]
return tmpKey
}
return key
}
/**
*
* @param {*} key | 要操作的键值
* @param {*} syncFlag | 同步状态,默认 false (异步),true 为同步
*/
get = (key, syncFlag = true) => {
// 有值默认取key值
if (key) {
// 判断值是否是指定的对象值
let tmpKey = this.checkKeyType(key, 1)
let isObjectKey = STORAGE_OBJECTkEY[tmpKey]
// console.log(key)
// console.log(isObjectKey)
if (isObjectKey) {
return this.getObjectKeyValue(isObjectKey)
} else {
throw new Error(`Storage ${this.types[1]} ${key}: key must be register`)
}
} else {
return this.getObjectKeyValue(DEFAULT_GET_STORAGEKEY)
}
}
/**
*
* @param {*} 空key返回默认定义数组的值
*/
getObjectKeyValue(key) {
// ObjectList
if (typeof key == 'string') {
key = this.addEvnToKey(key)
let res = wx.getStorageSync(key)
if (res) {
return JSON.parse(res)
} else {
// reject(errMsg)
return ''
}
} else {
let Obj = {}
key.forEach(key => {
let defaultKey = this.addEvnToKey(key)
let res = wx.getStorageSync(defaultKey)
Obj[key] = res ? JSON.parse(res) : ''
})
return Obj
}
}
/**
*
* @param {*} key | 要操作的键值
* @param {*} data | 要存储的值,会转换为 JSON 串进行存储
* @param {*} syncFlag | 同步状态,默认为同步 false (异步),true 为同步
*/
set = (key, data, syncFlag = true) => {
let tmpKey = this.checkKeyType(key, 2)
if (tmpKey) {
tmpKey = this.addEvnToKey(tmpKey)
const sucMsg = 'Storage set: set data successfully'
const errMsg = 'Storage set: failed to set data'
return new Promise((resolve, reject) => {
let tmpData = JSON.stringify(data)
if (syncFlag) {
try {
wx.setStorageSync(tmpKey, tmpData)
resolve(sucMsg)
} catch (err) {
console.log(err)
reject(errMsg)
}
} else {
wx.setStorage({
data: tmpData,
key: tmpKey,
success: () => {
resolve(sucMsg)
},
fail: err => {
console.log(err)
reject(errMsg)
}
})
}
})
}
}
/**
*
* @param {*} key | 要操作的键值,为空则清空所有,有值则清空指定的值
* @param {*} syncFlag | 同步状态,默认 false (异步),true 为同步
*/
rm = (key = '', syncFlag = false) => {
let tmpKey = this.checkKeyType(key, 3, false)
tmpKey = tmpKey.TrimStr()
const sucMsg = 'Storage rm: rm data successfully'
const errMsg = 'Storage rm: failed to rm data'
return new Promise((resolve, reject) => {
if (tmpKey == '') {
if (syncFlag) {
try {
wx.clearStorageSync()
resolve(sucMsg)
} catch (err) {
console.log(err)
reject(errMsg)
}
} else {
wx.clearStorage({
success: res => {
resolve(sucMsg)
},
fail: err => {
console.log(err)
reject(errMsg)
}
})
}
} else {
tmpKey = this.addEvnToKey(tmpKey)
if (syncFlag) {
try {
wx.removeStorageSync(tmpKey)
resolve(sucMsg)
} catch (err) {
console.log(err)
reject(errMsg)
}
} else {
wx.removeStorage({
key: tmpKey,
success: () => {
resolve(sucMsg)
},
fail: err => {
console.log(err)
reject(errMsg)
}
})
}
}
})
}
/**
* @description: key 拼接小程序环境变量
* @param {*} key | 要操作的键值,
* @returns {String} 拼接后的值
*/
addEvnToKey = key => {
// return // console.log(this.environment)
return `${this.environment}_${key}`
}
}
/** 去除前导空格和后导空格 */
String.prototype.TrimStr = function () {
return this.replace(/(^\s*)|(\s*$)/g, '')
}
export default Storage
// 实例化对象存储
import Storage from './storage'
const storage = new Storage()
// console.log(storage)
/** */
export function getSessionId() {
return storage.get('sessionId')
}
export function setSessionId(sessionId) {
storage.set('sessionId', sessionId)
}
export function getUserInfo() {
return storage.get('userInfo')
}
export function setUserInfo(data) {
storage.set('userInfo', data || {})
}
export function removeSystemStorage() {
// storage.rm('srcm_shopmall_user_info')
// storage.rm('scrm_shopmall_sessionId')
// storage.rm('guest_no')
// storage.rm('equity_info')
// storage.rm('packageList')
// storage.rm('isVIP')
// storage.rm('bizjiaUrl')
// storage.rm('vip_card_info')
}
export function setStorageSync(key, data) {
storage.set(key, JSON.stringify(data))
}
export function getStorageSync(key) {
return storage.get(key) || null
// JSON.parse(data)
}
/**设置标题栏 */
export function setNavigationBarTitleText(title) {
storage.set('app_title', title)
}
/**获取app标题 */
export function getNavigationBarTitleText() {
return storage.get('app_title')
}
/** 存储设备信息 */
export function setSystem_info(that) {
let info = storage.get('system_info')
!info &&
wx.getSystemInfo({
success(res) {
// console.log(res)
storage.set('system_info', res)
}
})
}
export default{
getSessionId,
setSessionId,
getUserInfo,
setUserInfo,
removeSystemStorage,
setStorageSync,
getStorageSync,
setNavigationBarTitleText,
getNavigationBarTitleText,
setSystem_info
}
/**获取用户信息 */
export function getUserInfo() {
let user = wx.p.storage.get('userInfo') || {}
return user
}
/**设置用户信息 */
export function setUserInfo(userInfo) {
wx.p.storage.set('userInfo', userInfo)
}
export function isMember(isNeedToHttp, callBack) {
if (isNeedToHttp) {
wx.p.api.equityApi.checkOpenMember().then(res => {
let flag = false
if (res.code == 0 && res.data) {
flag = true
}
wx.p.storage.set('isVIP', flag)
callBack && callBack(flag, res.data)
})
return
}
return wx.p.storage.get('isVIP') || false
}
export default{
getUserInfo,
setUserInfo,
isMember
}
// 缓存get方法为空的默认指定值
export const DEFAULT_GET_STORAGEKEY = ['sessionId', 'merchantId', 'userInfo']
// 缓存get方法key的对应才映射值
export const STORAGE_OBJECTkEY = {
system_info: 'system_info',
mock_data: 'mock_data',
merchant_info: 'merchant_info',
address_info: 'address_info',
userInfo: 'userInfo',
sessionId: 'sessionId',
bindInfo:'bindInfo',
unauthorized:'unauthorized',
wx_user_info:'wx_user_info'
}
export default{
DEFAULT_GET_STORAGEKEY,
STORAGE_OBJECTkEY
}
\ No newline at end of file \ No newline at end of file
/**emoji正则 */
const emojiReg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac])/g
/**过滤表情 */
export function haveEmoji(value) {
let val = false
value = value.replace(/\s/g, '').trimStart().trimEnd()
if (emojiReg.test(value) && !/\s/g.test(value)) {
showToast({
icon: 'error',
title: '不能输入表情'
})
val = true
}
return val
}
/**替换表情 */
export function replaceEmoji(value) {
let val = value.replace(emojiReg, '')
return val.trimStart().trimEnd()
}
export default{
emojiReg,
haveEmoji,
replaceEmoji
}
class Bus {
constructor() {
this.events = {}
}
on(Event, cb) {
if(this.events[Event]) {
this.events[Event].push(cb);
} else {
this.events[Event] = [cb];
}
// 如果是匿名函数就给用户个警告
if(!cb.name) {
console.warn('on 接口的 handler 参数推荐使用具名函数。具名函数可以使用 off 接口取消订阅,匿名函数无法取消订阅。')
}
}
emit(Event, obj) {
if(!this.events[Event]) return
this.events[Event].forEach(cb => {
cb(obj)
})
}
off(Event,cb) {
if(!this.events[Event]) return
const index = this.events[Event].findIndex(item => item === cb);
if (index === -1) {
// console.error(new Error('该 handle 没有订阅者,取消订阅失败'));
return;
}
this.events[Event].splice(index, 1);
}
// 给这个类加一个静态方法,用来判断这个类之前有没有生成过对象
static getInstance() {
if (!Bus.instance) {
Bus.instance = new Bus()
}
return Bus.instance;
}
}
// 导出这里返回 Bus 类静态 getInstance 的执行结果
export default Bus.getInstance();
\ No newline at end of file \ No newline at end of file
/** 根据时间回显时间格式 */
export function timeAgo(dateTimeStamp) {
let result = '刚刚'
let minute = 1000 * 60
let hour = minute * 60
let day = hour * 24
let now = new Date().getTime() //获取当前时间毫秒
let diffValue = now - dateTimeStamp //时间差
let todayValue = new Date()
todayValue.setHours(0)
todayValue.setMinutes(0)
todayValue.setSeconds(0)
todayValue.setMilliseconds(0)
let todayTimeStamp = todayValue.getTime() //获取当天零时毫秒
if (diffValue < 0) {
return result
}
let diffTodayValue = todayTimeStamp - dateTimeStamp
//计算时间差的分,时,天,周,月
let minC = diffValue / minute
let hourC = diffValue / hour
let dayC = diffTodayValue / day
if (diffTodayValue > 0) {
if (dayC >= 2) {
return new Date(dateTimeStamp).format('MM月dd日 hh:mm:ss')
}
if (dayC >= 1 && dayC < 2) {
return '前天' + new Date(dateTimeStamp).format(' hh:mm:ss')
}
return '昨天' + new Date(dateTimeStamp).format(' hh:mm:ss')
}
if (hourC >= 1 && hourC <= 23) {
return parseInt(hourC) + '小时前'
}
if (minC >= 1 && minC <= 59) {
return parseInt(minC) + '分钟前'
}
if (diffValue >= 0 && diffValue <= minute) {
return '刚刚'
}
return new Date(dateTimeStamp).format('MM月dd日 hh:mm:ss')
}
//用来判断评论时间
export function commentTime(dateTimeStamp) {
var result
let time = dateTimeStamp
let nowTime = new Date().getTime()
let timeDifference = nowTime - time
let minTime = 60000
let hourTime = minTime * 60
let dayTime = hourTime * 24
let weektTime = dayTime * 7
let monthTime = dayTime * 30
let yearTime = dayTime * 365
if (Math.floor(timeDifference / yearTime) >= 1) {
result = Math.floor(timeDifference / yearTime) + '年前'
} else if (Math.floor(timeDifference / monthTime) >= 1) {
result = Math.floor(timeDifference / monthTime) + '月前'
} else if (Math.floor(timeDifference / weektTime) >= 1) {
result = Math.floor(timeDifference / weektTime) + '周前'
} else if (Math.floor(timeDifference / dayTime) >= 1) {
result = Math.floor(timeDifference / dayTime) + '天前'
} else if (Math.floor(timeDifference / hourTime) >= 1) {
result = Math.floor(timeDifference / hourTime) + '小时前'
} else if (Math.floor(timeDifference / minTime) >= 1) {
result = Math.floor(timeDifference / minTime) + '分钟前'
if (Math.floor(timeDifference / minTime) <= 5) {
//五分钟内就是刚刚
result = '刚刚'
}
}
return result
}
/**IOS时间兼容 */
export function iosTimeFormat(time) {
if (!time) return ''
return typeof time != 'string' ? time : time.replace(/\-/g, '/')
}
/**获取时间段总时长 */
export function getScopeTime(inputTime, curTime) {
let obj = {
text: '-',
day: 0,
isDanger: false
}
if (!inputTime || arguments.length === 0) return obj
let time = curTime / 1000 - inputTime / 1000
if (time < 60) {
let s = parseInt(time)
obj.text = `00:00:${s}`
} else if (time < 3600) {
let m = parseInt(time / 60)
let s = parseInt(time % 60)
m = m < 10 ? `0${m}` : m
s = s < 10 ? `0${s}` : s
obj.text = `00:${m}:${s}`
} else if (time < 86400) {
let h = parseInt(time / 3600)
let min = time - h * 3600
let m = parseInt(min / 60)
let s = parseInt(time % 60)
m = m < 10 ? `0${m}` : m
s = s < 10 ? `0${s}` : s
obj.text = `${h}:${m}:${s}`
} else if (time > 86400) {
let day = parseInt(time / 86400)
let hour = time - day * 86400
let h = parseInt(hour / 3600)
let min = hour - h * 3600
let m = parseInt(min / 60)
let s = parseInt(time % 60)
h = h < 10 ? `0${h}` : h
m = m < 10 ? `0${m}` : m
s = s < 10 ? `0${s}` : s
if (day > 7 || (day == 7 && h > 0)) obj.isDanger = false
obj.day = day
obj.text = `${day}天${h}:${m}:${s}`
}
return obj.text
}
/**num:要转换的数值,fixed:精确几位小数 */
export function decimal(num, fixed = 2) {
const pow = Math.pow(10, fixed)
return Number(Math.round(num * pow) / pow)
}
/**分转元 */
export function centsToyuan(price) {
// console.log(decimal)
return decimal(price / 100, 2).toFixed(2)
}
/**设置价格 */
export function setPrice(price) {
let [num, decimal] = price.toString().split('.')
if (!decimal) decimal = '00'
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + `.${decimal}`
}
export default{
timeAgo,
commentTime,
iosTimeFormat,
getScopeTime,
decimal,
centsToyuan,
setPrice
}
import util from './util'
import wxApi from './utils_wx'
import constants from './constants'
import draw from './draw'
import emoji from './emoji'
import eventbus from './eventbus'
import format from './format'
import network from './network'
import routerApi from './routerApi'
import WxValidate from './WxValidate'
import cache from './cache/index'
module.exports ={util,wxApi,constants,draw,emoji,eventbus,format,network,routerApi,WxValidate,cache}
\ No newline at end of file \ No newline at end of file
const ISCOMMECTED = Symbol('ISCOMMECTED')
class NetWork {
[ISCOMMECTED] = false;
constructor() {
this.onNetworkStatusChange()
}
/**监听网络变化 */
onNetworkStatusChange() {
wx.onNetworkStatusChange(({
isConnected,
networkType
}) => {
if (!isConnected && !this[ISCOMMECTED]) {
this[ISCOMMECTED] = true
wx.showToast({
icon: 'loading',
title: '网络尚未连接',
mask: true,
duration: 36e3 * 24
})
} else {
if (this[ISCOMMECTED]) {
const thisPage = wx.p.router.getPageInstance(),
options = Object.keys(thisPage.options)
this[ISCOMMECTED] = false
wx.showLoading()
wx.hideLoading()
// if (thisPage.noPageAuth) {
// wx.showLoading()
// this.refreshPage()
// } else {
// let url = `/${thisPage.route}`
// if (options.length) {
// let query = []
// options.map(key => {
// query.push(`${key}=${thisPage.options[key]}`)
// })
// url += `?${query.join('&')}`
// }
// wx.p.router.redirectTo('login.loading', {
// url
// })
// }
}
}
})
}
getNetworkType() {
const that = this
return new Promise((resolve, reject) => {
wx.getNetworkType({
success({
networkType
}) {
that[ISCOMMECTED] = networkType == 'none'
resolve(networkType)
},
fail: err => reject(err)
})
})
}
netWorkModal(confirmText = '返回') {
return new Promise((resolve, reject) => {
wx.showModal({
content: '网络尚未连接,请稍后再试',
confirmText,
showCancel: false,
confirmColor: '#3666FE',
success(res) {
if (res.confirm) resolve()
if (res.cancel) reject()
}
})
})
}
/**页面重载 */
refreshPage() {
wx.hideLoading()
wx.showNavigationBarLoading()
const thisPage = wx.p.router.getPageInstance(),
{
onLoad,
onShow,
options
} = thisPage
if (onLoad) thisPage.onLoad(options, true)
if (onShow) thisPage.onShow(options, true)
}
}
export default new NetWork()
\ No newline at end of file \ No newline at end of file
/** */
export function getSceneId(path) {
let [_route_, _options_] = path.split('?')
let [target] = _route_.split('/')
let name = _route_.split('/').pop()
let scene = _options_ ? _options_.split('=')[1] : ''
return {
name,
scene,
target
}
}
/**
* 获取url参数
*/
export function filterUrlParam(urlSearch) {
let ret = {}
let regParam = /([^&=]+)=([\w\W]*?)(&|$|#)/g
if (urlSearch) {
var strParam = urlSearch
var result
while ((result = regParam.exec(strParam)) != null) {
ret[result[1]] = result[2]
}
}
return ret
}
/**跳转至购物车 */
export function goShoppingCart() {
wx.p.router.go('packageMall.shoppingCart')
}
export function decodeUrlLink(options) {
let op = {}
let query = Object.keys(options)
if (query.length) {
try {
query.map(e => {
let params = decodeURIComponent(e).split('&')
params.map((i, index) => {
let [key, val] = i.split('=')
if (val) op[key] = val
if (index == params.length - 1) {
throw op
}
})
})
} catch (res) {
let that = wx.p.router.getPageInstance()
that.onLoad(res)
}
}
}
export default{
getSceneId,
filterUrlParam,
goShoppingCart,
decodeUrlLink
}
\ No newline at end of file \ No newline at end of file
import { dsnUrl } from "~/config";
import { Sentry } from "~/lib/index";
export default function sentryInit() {
// accountInfo.miniProgram.envVersion == 'release' &&
const accountInfo = wx.getAccountInfoSync();
//测试和生产才开发sentry
const env = ["trial", "release"];
env.includes(accountInfo.miniProgram.envVersion) &&
Sentry.init({
// dsn: 'http://ebcf31c417cc4ce185782f046e4a87a2@sentry.glsx.com.cn/5'
dsn: dsnUrl,
});
}
/** 分享
* @param {*} shareTitle 分享标题
* @param {*} sharePath 分享页面路径 不传默认当前页
* @param {*} shareImage 分享图片 不传默认当前页面截图
* @param {*} shareQuery 分享页面参数
* @param {*} noPageAuth 分享页面是否需要登录拦截
* @param {*} shareFun 分享页面
* @param {*} shareTrackData 分享埋点数据
* @param {*} onViewTrack 开启浏览埋点
* @returns
*/
// import { reportData } from '~/api/index.js'
class Share {
constructor() {
console.log('---------------- 分享初始化 ----------------')
this.initPageProxy()
}
/**全局注册事件 */
initPageProxy() {
let thisPage = Page
let _this = this
Page = function (el) {
try {
el || (el = {}), _this.pageLeaveProxy(el), thisPage.apply(this, arguments)
} catch (el) {
thisPage.apply(this, arguments)
}
}
}
/**设置全局分享 */
pageLeaveProxy(page) {
const onLoad = page.onLoad,
that = this
if (page.onShareAppMessage) {
const that = this
page.onShareAppMessage = function () {
let { shareTitle, sharePath, shareImage, shareQuery, noPageAuth, shareFun, shareTrackData } = this,
path = `/${this.route}`
if (sharePath) path = `/${sharePath}`
path += that.setCommonShareQuery()
if (shareQuery) path += `&${shareQuery}`
console.log('===============', path)
if (!noPageAuth) path = `/pages/loading/loading?url=${encodeURIComponent(path)}`
if (shareFun) shareFun()
// if (shareTrackData) that.reportShareData(shareTrackData)
console.table( {
path,
title: shareTitle,
imageUrl: shareImage
})
return {
path,
title: shareTitle,
imageUrl: shareImage
}
}
}
if (page.onShareTimeline) {
page.onShareTimeline = function () {
let { shareTitle, shareImage, shareQuery, shareFun, shareTrackData } = this
if (shareFun) shareFun()
// if (shareTrackData) that.reportShareData(shareTrackData)
shareQuery = that.setCommonShareQuery(shareQuery)
console.log(shareQuery)
return {
query: shareQuery,
title: shareTitle,
imageUrl: shareImage
}
}
}
page.onLoad = async function () {
onLoad && onLoad.apply(this, arguments)
if (this.onViewTrack) {
// const WXUSERINFO = await USERAPI.getWXUserInfo(),
// { USERINFO } = that.getCommonData(),
// shareInfo = this.options
// if (shareInfo.shareOpenId)
// reportData(
// {
// openId: WXUSERINFO.openId || '',
// unionId: WXUSERINFO.unionId || '',
// nickName: WXUSERINFO.nickName || '',
// avatar: WXUSERINFO.avatarUrl || '',
// phone: WXUSERINFO.phone || USERINFO.phone || '',
// ...shareInfo
// },
// 1
// )
}
}
}
getCommonData() {
const WXUSERINFO = wx.p.storage.get('wx_user_info'), //针对没登录用户,有openid
USERINFO = wx.p.storage.get('userInfo') //这个是针对登录的
return {
WXUSERINFO,
USERINFO
}
}
setCommonShareQuery(query) {
const { WXUSERINFO, USERINFO } = this.getCommonData(),
thisPage = wx.p.router.getPageInstance().options
query = `${query ? `?${query}&` : '?'}merchantId=${thisPage.merchantId || USERINFO.merchantId || ''}&shareOpenId=${thisPage.shareOpenId || WXUSERINFO.openId || ''}&sharePhone=${thisPage.sharePhone || USERINFO.phone || ''}`
return query
}
reportShareData(shareTrackData) {
const { WXUSERINFO, USERINFO } = this.getCommonData(),
thisPage = wx.p.router.getPageInstance().options
reportData({
openId: WXUSERINFO.openId || '',
unionId: WXUSERINFO.unionId || '',
nickName: WXUSERINFO.nickName || '',
avatar: WXUSERINFO.avatarUrl || '',
phone: WXUSERINFO.phone || '', //浏览用户授权的手机号
merchantId: thisPage.merchantId || USERINFO.merchantId || '',
shareOpenId: thisPage.shareOpenId || WXUSERINFO.openId || '',
sharePhone: thisPage.sharePhone || USERINFO.phone || '', //登陆人,服务商的手机号
...shareTrackData
})
}
}
export default new Share()
/**
*/
import mapApi from '../mapapi/mapapi'
import api from '~/api/request/http'
import { getUserInfo } from '~/utils/cache/userInfo'
// 实例化对象存储
import { Storage } from '~/utils/cache/storage'
const $Storage = new Storage()
let TRACK_TIME = null,
ADDRESS_INFO = null
const track_interval_time = 60 * 1e3
class TRACK {
constructor() {
console.log('---------------- 埋点初始化 ----------------')
this.initPageProxy()
// this.sendTrack()
//this.getAddressInfo().then(res => (ADDRESS_INFO = res))
// this.appHide()
}
/**监听页面 */
pageLeaveProxy(thisPage) {
let _this = this,
onHide = thisPage.onHide,
onUnload = thisPage.onUnload,
onLoad = thisPage.onLoad,
onShow = thisPage.onShow,
onTabItemTap = thisPage.onTabItemTap
thisPage.onTabItemTap = function (options) {
onTabItemTap && onTabItemTap.apply(this, arguments)
// , _this.setTrack({}, 1)
}
thisPage.onLoad = function () {
onLoad && onLoad.apply(this, arguments)
//, _this.setTrack({
// enterTime: new Date().format('yyyy-MM-dd hh:mm:ss')
// })
}
thisPage.onShow = function () {
onShow && onShow.apply(this, arguments)
// , (_this.getPageInstance().page_show_time = Date.now())
}
thisPage.onHide = function () {
let { page_show_time } = _this.getPageInstance()
onHide && onHide.apply(this, arguments)
// ,_this.setTrack(
// {
// duration: getDuration(page_show_time)
// },
// 2
// )
}
thisPage.onUnload = function () {
let { page_show_time } = _this.getPageInstance()
onUnload && onUnload.apply(this, arguments)
// ,_this.setTrack(
// {
// duration: getDuration(page_show_time)
// },
// 2
// )
}
const getDuration = page_show_time => (Date.now() - page_show_time) / 1e3
}
/**全局注册事件 */
initPageProxy() {
let thisPage = Page
let _this = this
Page = function (el) {
try {
el || (el = {}), _this.pageLeaveProxy(el), thisPage.apply(this, arguments)
} catch (el) {
thisPage.apply(this, arguments)
}
}
}
appShow() {
wx.onAppShow(() => {
// if (TRACK_TIME) clearInterval(TRACK_TIME)
// this.sendTrack()
// wx.offAppShow()
// this.appHide()
// console.log('---------------- 重新打开埋点 ----------------')
})
}
appHide() {
wx.onAppHide(() => {
// if (TRACK_TIME) clearInterval(TRACK_TIME)
// wx.offAppHide()
// this.appShow()
// console.log('---------------- APP隐藏 埋点停止推送 ----------------')
})
}
/**设置埋点数据 */
setTrack() {}
getGuestNo() {
let guest_no = $Storage.get('guest_no')
if (!guest_no) {
guest_no = this.setGuestNo()
$Storage.set('guest_no', guest_no)
}
return guest_no
}
/**定时发送埋点数据 */
sendTrack() {
TRACK_TIME = setInterval(() => {
let prepare_data = $Storage.get('prepare_data')
let data = {
method: 'entmicro.api.customercollect.reportCustomerList',
jsonList: prepare_data
}
if (prepare_data && prepare_data.length)
api.post(data, true).then(({ code, data, message }) => {
if (code == 0 && data) {
$Storage.set('prepare_data', [])
console.log('---------------- 埋点定时推送成功 ----------------', new Date().format('yyyy-MM-dd hh:mm:ss'), ':', prepare_data)
} else console.log('---------------- 埋点定时推送失败 ----------------', new Date().format('yyyy-MM-dd hh:mm:ss'), ':', message)
})
}, track_interval_time)
}
/**获取页面对象实例 */
getPageInstance = (size = 1) => {
const pages = getCurrentPages()
return pages[pages.length - size]
}
/**获取页面标题 */
getPageTitle() {
let { route, navigationBarTitleText } = this.getPageInstance()
if ('\u672a\u53d6\u5230' === route || !route) return ''
let title = ''
if (__wxConfig) {
let { window } = __wxConfig.page[`${route}.html`]
title = window.navigationStyle == 'custom' ? navigationBarTitleText : window.navigationBarTitleText
}
if (!title) title = '广联数科EHR系统'
return title
}
/**获取设备信息 */
getSystemInfo() {
let { SDKVersion, brand, model, system, version } = $Storage.get('system_info')
return {
SDK_version: SDKVersion,
brand,
model,
system,
version
}
}
/**获取门店信息 */
getMerchantInfo() {
let { merchantId } = $Storage.get('merchant_info')
return {
merchant_id: merchantId
}
}
/**获取用户位置信息 */
getAddressInfo() {
let addressInfo = $Storage.get('address_info')
return new Promise(resolve => {
if (addressInfo && Date.now() - addressInfo.createTime < 2 * 60 * 1e3) resolve(addressInfo)
else
wx.getLocation({
type: 'gcj02'
}).then(({ latitude, longitude }) => {
if (!addressInfo) this.setTrack({}, 5)
console.log('---------------- 更新地理位置 ----------------')
mapApi.detailedAdrress([latitude, longitude]).then(detail => {
let info = {
...detail,
createTime: Date.now()
}
resolve(info)
$Storage.set('address_info', info)
})
})
})
}
/**获取游客ID */
setGuestNo(length = 30) {
let name = '',
n = ['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 < Number(length); i++) {
name += n[Math.round(Math.random() * (n.length - 1))]
}
return `GH_${name}_${Date.now()}`
}
}
wx.$Track = new TRACK()
/**
* 日期格式化
* let time = new Date().format('yyyy-MM-dd hh:mm:ss') //log 2020-07-31 10:00:00
*/
Date.prototype.format = function (fmt) {
let o = {
'M+': this.getMonth() + 1, //月份
'd+': this.getDate(), //日
'h+': this.getHours(), //小时
'm+': this.getMinutes(), //分
's+': this.getSeconds(), //秒
//季度
'q+': Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds() //毫秒
}
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
}
return fmt
}
/**触底加载 */
const onReachBottom = (obj, callBack) => {
let _this = obj._this || wx.p.router.getPageInstance()
let {
pageNum,
total,
pageSize,
nothing
} = obj
if (!total && !pageNum) {
console.error('total&&pageNum为必传')
return
}
if (!pageSize) pageSize = 10
if (!nothing) nothing = 'nothing'
if (Math.ceil(total / pageSize) > pageNum) {
_this.setData({
pageNum: pageNum + 1
})
callBack()
} else {
_this.setData({
[nothing]: true
})
}
}
/**节流 */
const throttle = (fn, gapTime) => {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
// 返回新的函数
return function () {
let _nowTime = +new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments) //将this和参数传给原函数
_lastTime = _nowTime
}
}
}
/**删除对象里的null值 */
const clearObjNull = options => {
let obj = {}
Object.keys(options).map(e => {
if (options[e] != null && options[e] != undefined) {
if (typeof options[e] == 'object') {
Object.keys(options[e]).map(key => {
if (options[e][key] == null || options[e][key] == undefined) delete options[e][key]
})
}
obj[e] = options[e]
}
})
return obj
}
/**
* 判断是否是空对象
* @param {*} obj 传进来的对象
* @returns
*/
const isEmptyObj = obj => {
return JSON.stringify(obj) === '{}'
}
// 解析参数成对象 "actNum=1&activeNavIdx=0&isShare=true"
const parseString = str => {
// console.log('str: ', str);
if (!str) return
let obj = {}
let strArr = str.split('&')
// console.log('strArr: ', strArr);
strArr.forEach(item => {
// console.log("item: ", item);
let keyArr = item.split('=')
obj[keyArr[0]] = keyArr[1]
})
return obj
}
const Util = {
onReachBottom,
clearObjNull,
throttle,
isEmptyObj,
parseString,
}
export default Util
\ No newline at end of file \ No newline at end of file
import {wxqrcode} from '~/lib/index.js'
/**
* 禁止滑动
*/
const noScroll = () => {}
/**设置粘贴板内容 */
const setCopyData = (data, callBack) => {
wx.setClipboardData({
data: data,
success(res) {
if (callBack && typeof callBack === 'function') callBack(res)
}
})
}
/**
* 防止重复点击
*/
const showLoading = (title = '') => {
if (wx.showLoading) {
// 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
wx.showLoading({
title,
mask: true
})
} else {
// 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
wx.showToast({
title,
icon: 'loading',
mask: true,
duration: 20000
})
}
}
const hideLoading = () => {
if (wx.hideLoading) {
// 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
wx.hideLoading()
} else {
wx.hideToast()
}
}
const showToast = val => {
let obj = {}
if (val && typeof val === 'string') {
obj.title = val
obj.icon = 'none'
} else {
obj = val
}
return wx.showToast(obj)
}
/**获取设备信息 */
const getSystemInfo = callBack => {
wx.getSystemInfo({
success(res) {
callBack(res)
},
fail(err) {
callBack(err)
}
})
}
/**拨打电话 */
const phoneCall = phoneNumber => {
wx.makePhoneCall({
phoneNumber: `${phoneNumber}`
})
}
/**查看大图 */
const previewImage = params => {
wx.previewImage(params)
}
export function handleCopy(url) {
// var { idx } = e.currentTarget.dataset
// var currentItem = this.data.orderObj.activityList[idx]
var qr = wxqrcode.createQrCodeImg(url)
const base64src = function (base64data) {
return new Promise((resolve, reject) => {
const [a, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []
if (!format) reject(new Error('ERROR_BASE64SRC_PARSE'))
const filePath = `${wx.env.USER_DATA_PATH}/tmp_base64src.${format}`
const buffer = wx.base64ToArrayBuffer(bodyData)
wx.getFileSystemManager().writeFile({
filePath,
data: buffer,
encoding: 'binary',
success() {
resolve(filePath)
},
fail() {
reject(new Error('ERROR_BASE64SRC_WRITE'))
}
})
})
}
base64src(qr).then(res => {
console.log(res)
wx.getImageInfo({
src: res,
success(obj) {
wx.showShareImageMenu({
path: obj.path
})
},
fail() {}
})
})
}
/**获取节点信息
* name(id获取class)
* callBack 回调函数
* componentThis是否在组件 (传组件this)
*/
const getViewInfo = (name, callBack, componentThis) => {
const query = !componentThis ? wx.createSelectorQuery() : wx.createSelectorQuery().in(componentThis)
query
.selectAll(name)
.boundingClientRect(res => {
callBack(res[0])
})
.exec()
}
/** 获取小程序 appId */
const getAppId = () => {
return wx.getAccountInfoSync().miniProgram.appId
}
const wxApi = {
previewImage,
getSystemInfo,
showLoading,
hideLoading,
setCopyData,
showToast,
phoneCall,
noScroll,
getViewInfo,
getAppId
}
export default wxApi
分类逻辑是 按功能区分 有多个相关就分类成一个文件夹 没有就单独一个文件
|-- utils
​ |-- constantData.js //静态变量导出
​ |-- Draw.js //画图方法
​ |-- emoji.js //表情方法相关
​ |-- evenbus.js //组件事件传递(已默认挂载在wx.$event)
​ |-- format.js (格式化 例如日期和价格)
​ |-- funcProtypeExtend.js (为函数挂hook)
​ |-- routerApi.js (处理路由相关的 参数解析和调整)
​ |-- util.js (处理wx对应api的方法)
​ |-- watch.js (实现vue watch功能)
​ |-- WxValidate.js (表单校验方法)
​ |-- cache (缓存相关)
​ | |-- storage.js (默认挂载在wx.p.storage)
​ | |-- storageApi.js ()
​ | |-- userInfo.js
​ |-- lib (导入的文件 跟业务没啥关系)
​ | |-- sentry-miniapp.js
​ | |-- wx-promise-pro.js
​ | |-- wxqrcode.js
​ | |-- wxUpdateManager.js
​ | |-- md5.js
| |-- sha1.js
| |-- qs.js
​ |-- mapapi (地图需要导入配置)
​ | |-- mapapi.js
​ |-- request (请求相关)
​ | |-- environment.js (切换请求环境 根据index )
​ | |-- http.js
​ | |-- request.js (封装的请求方法)
​
​ |-- track (埋点相关)
​ |-- Track.js
# 小程序模板 说明
<img src="./小程序通用模板文件结构.jpg" style="zoom:25%;" />
## 命名规范
小程序 components 组件文件夹命名规则是 第一个字母大写
其他文件适用驼峰规则
utils/constantData 文件为配置常量用 使用全大写加下滑线拼接
```js
const IMG_URL = 'xxx'
```
## 小程序配置sass
在project.config.json增加如下配置,对应页面新增.sass 编写即可
存在问题:
1. 小程序开发工具没有配套对应代码高亮功能, 可以vscode安装 sass 和Beautify css/sass/scss/less做代码高亮和格式化 然后在微信开发者工具中的拓展 选择从vscode 导入即可以实现高亮
2. 无法使用sass 的mixin功能
```
{
"setting": {
"useCompilerPlugins": [
"less"
]
}
}
```
Tips: 编译优先级 wxss>saas 或 wxss>less
## 小程序配置绝对路径
在 app.json 文件 新增 下面配置即可实现 [官方文档地址](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#resolveAlias)
```
~/* 使用时的路径前缀 /* 根目录下对应的文件名字
"resolveAlias": {
"~/*": "/*"
},
```
## stroage 存储使用说明
可点击查看[流程调用图](https://www.yuque.com/docs/share/fb9ef957-acd8-412b-9653-e7a4eb160876?# 《小程序缓存功能》)
默认小程序实例化时已自带挂载在全局对象下 无需单独引入 只需要获取全局小程序对象调用即可
使用promise风格处理成功结果then里面获取,处理失败catch获取
方法有三个方法(注意! rm方法无key值为清空全部存储值)
get: 通过 wx.p.storage.get 调用
​ 输入值: 1.key对象 2. syncFlag (同步状态,true 为同步, false (异步),默认)
key为空值会返回默认定义的数组集合参数 为关键字则返回定义的数组集合参数 (这个方法是一个对象)
都不是则作为取值的key
​ 输出: 对应key值的JSON.parse 内容(没有对应的key 默认返回空)
set: 通过 $storage.set 或setStorage 调用
​ 输入值: 1.key对象
​ 2.data | 要存储的值,会转换为 JSON 串进行存储
​ 3.syncFlag (同步状态,默认 false (异步),true 为同步)
​ 输出: 存储成功或错误提示
rm: 通过 $Storage.rm 或rmStorage 调用
​ 输入值: 1.key对象 | 要操作的键值,为空则清空所有,有值则清空指定的值
​ 2.syncFlag | 同步状态,默认 false (异步),true 为同步
​ 输出: 删除key值的成功或错误提示
```javascript
代码示例
设置缓存
wx.p.storage
.set('aaa', { a: 'a', b: 'b' })
.then(res => {
//成功之后的逻辑代码
})
.catch(err => {
console.log(err)
})
取变量方法 默认同步取值写法(没有值是返回空值回来)
wx.p.storage.get('key值')
异步写法
wx.p.storage.get('key值',false).then((result)=>console.log(result)).catch((error)=>)
```
## 路由钩子使用说明
| - utils
​ | - funcProtypeExtend.js 扩展函数原型上的方法
| - router
​ | - index.js 最终生成导出路由实例文件,包含前置、后置钩子逻辑
​ | - router.js 路由实例类,分享了一些路由常用的方法,跳转,返回等
​ | - routerBefore.js 路由前置钩子的业务逻辑(后置钩子类似)
​ | - routers.js 生成特定格式的路由配置
​ | - wxOnAppRoute.js 执行wx.onAppRoute期间的钩子
使用方法:在/router/index.js下
```javascript
import routerBefore from "./routerBefore.js";
// 添加路由前置后置钩子
let routerInstance = () => {
return new Router(routes);
};
routerInstance = routerInstance
.before(function () {
console.log("前置");
/**处理前置钩子逻辑 */
routerBefore()
})
.after(function () {
/**处理后置钩子逻辑 */
console.log("后置");
});
在routerBefore.js文件写上相应的逻辑即可完成前置的一些逻辑,路由后置钩子类似。
```
## 提示统一管理
| - utils
​ | - wxShowToast.js 微信校验通知类工具封装
使用方式,用法,参数和**wx**的**showToast**用法一致
```js
import wxShowToast from './utils/wxShowToast.js'
使用方法一:wxShowToast(name,params)
使用内置的文本,以 tipsObj 中 phone 为例:(tipsObj可扩展)
wxShowToast('phone',{duration:2000})
使用方法二:wxShowToast(params)
完全自定义里边的参数,与wx的showToast一致:
wxShowToast({
title: '成功',
icon: 'success',
duration: 2000
})
```
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!