提交 587406a3 authored 作者: 黄旭新's avatar 黄旭新

引入微信SDK

上级 d92c6725
<script>
import api from '@/static/util/api.js'
import {post,get} from '@/static/util/fun.js'
import jweixin from 'jweixin-module'
export default {
onLaunch: function() {
console.log('App Launch')
},
created() {
let that=this
//请求接口获取签名时间戳
post(api.sign).then(res=>{
if(res.code==200){
that.timestamp=res.data.timestamp
that.nonceStr=res.data.nonceStr
that.signature=res.data.signature
jweixin.config({
debug: false,
appId: 'wx85eaf2734af145bd',
timestamp: that.timestamp,
nonceStr: that.nonceStr,
signature:that.signature,
jsApiList: ['updateTimelineShareData','updateAppMessageShareData','scanQRCode']
});
jweixin.ready(function() {
if(that.ispause){
innerAudioContext.pause();
}else{
innerAudioContext.play();
}
//分享给朋友接口
jweixin.updateAppMessageShareData({
title: '敏捷集团党史知识竞赛', // 分享标题
desc: '我在参加敏捷集团党史知识竞赛,一起来战吧!', // 分享描述
link: 'https://faces.diaosaas.com/party-history-h5/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: 'https://faces.diaosaas.com/party-history-h5/mp3/wxshare.png', // 分享图标
success: function () {
console.log('分享成功!')
}
})
//分享到朋友圈接口
jweixin.updateTimelineShareData({
title: '敏捷集团党史知识竞赛', // 分享标题
link: 'https://faces.diaosaas.com/party-history-h5/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: 'https://faces.diaosaas.com/party-history-h5/mp3/wxshare.png', // 分享图标
success: function () {
// 设置成功
console.log('分享成功!')
}
})
});
}
})
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
},
methods:{
jssdk(){
}
}
}
</script>
<style>
<style lang="scss">
@import 'uview-ui/index.scss';
/*每个页面公共css */
view {
box-sizing: border-box;
}
image {
width: 100%;
height: 100%;
}
</style>
# jweixin-module
微信JS-SDK
## 安装
### NPM
```shell
npm install jweixin-module --save
```
### UMD
```http
https://unpkg.com/jweixin-module/out/index.js
```
## 使用
```js
var jweixin = require('jweixin-module')
jweixin.ready(function(){
// TODO
});
```
## 完整API
>[微信JS-SDK说明文档](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115)
!function(e,n){"function"==typeof define&&(define.amd||define.cmd)?define(function(){return n(e)}):n(e,!0)}(window,function(o,e){if(!o.jWeixin){var n,c={config:"preVerifyJSAPI",onMenuShareTimeline:"menu:share:timeline",onMenuShareAppMessage:"menu:share:appmessage",onMenuShareQQ:"menu:share:qq",onMenuShareWeibo:"menu:share:weiboApp",onMenuShareQZone:"menu:share:QZone",previewImage:"imagePreview",getLocation:"geoLocation",openProductSpecificView:"openProductViewWithPid",addCard:"batchAddCard",openCard:"batchViewCard",chooseWXPay:"getBrandWCPayRequest",openEnterpriseRedPacket:"getRecevieBizHongBaoRequest",startSearchBeacons:"startMonitoringBeacons",stopSearchBeacons:"stopMonitoringBeacons",onSearchBeacons:"onBeaconsInRange",consumeAndShareCard:"consumedShareCard",openAddress:"editAddress"},a=function(){var e={};for(var n in c)e[c[n]]=n;return e}(),i=o.document,t=i.title,r=navigator.userAgent.toLowerCase(),s=navigator.platform.toLowerCase(),d=!(!s.match("mac")&&!s.match("win")),u=-1!=r.indexOf("wxdebugger"),l=-1!=r.indexOf("micromessenger"),p=-1!=r.indexOf("android"),f=-1!=r.indexOf("iphone")||-1!=r.indexOf("ipad"),m=(n=r.match(/micromessenger\/(\d+\.\d+\.\d+)/)||r.match(/micromessenger\/(\d+\.\d+)/))?n[1]:"",g={initStartTime:L(),initEndTime:0,preVerifyStartTime:0,preVerifyEndTime:0},h={version:1,appId:"",initTime:0,preVerifyTime:0,networkType:"",isPreVerifyOk:1,systemType:f?1:p?2:-1,clientVersion:m,url:encodeURIComponent(location.href)},v={},S={_completes:[]},y={state:0,data:{}};O(function(){g.initEndTime=L()});var I=!1,_=[],w={config:function(e){B("config",v=e);var t=!1!==v.check;O(function(){if(t)M(c.config,{verifyJsApiList:C(v.jsApiList),verifyOpenTagList:C(v.openTagList)},function(){S._complete=function(e){g.preVerifyEndTime=L(),y.state=1,y.data=e},S.success=function(e){h.isPreVerifyOk=0},S.fail=function(e){S._fail?S._fail(e):y.state=-1};var t=S._completes;return t.push(function(){!function(){if(!(d||u||v.debug||m<"6.0.2"||h.systemType<0)){var i=new Image;h.appId=v.appId,h.initTime=g.initEndTime-g.initStartTime,h.preVerifyTime=g.preVerifyEndTime-g.preVerifyStartTime,w.getNetworkType({isInnerInvoke:!0,success:function(e){h.networkType=e.networkType;var n="https://open.weixin.qq.com/sdk/report?v="+h.version+"&o="+h.isPreVerifyOk+"&s="+h.systemType+"&c="+h.clientVersion+"&a="+h.appId+"&n="+h.networkType+"&i="+h.initTime+"&p="+h.preVerifyTime+"&u="+h.url;i.src=n}})}}()}),S.complete=function(e){for(var n=0,i=t.length;n<i;++n)t[n]();S._completes=[]},S}()),g.preVerifyStartTime=L();else{y.state=1;for(var e=S._completes,n=0,i=e.length;n<i;++n)e[n]();S._completes=[]}}),w.invoke||(w.invoke=function(e,n,i){o.WeixinJSBridge&&WeixinJSBridge.invoke(e,x(n),i)},w.on=function(e,n){o.WeixinJSBridge&&WeixinJSBridge.on(e,n)})},ready:function(e){0!=y.state?e():(S._completes.push(e),!l&&v.debug&&e())},error:function(e){m<"6.0.2"||(-1==y.state?e(y.data):S._fail=e)},checkJsApi:function(e){M("checkJsApi",{jsApiList:C(e.jsApiList)},(e._complete=function(e){if(p){var n=e.checkResult;n&&(e.checkResult=JSON.parse(n))}e=function(e){var n=e.checkResult;for(var i in n){var t=a[i];t&&(n[t]=n[i],delete n[i])}return e}(e)},e))},onMenuShareTimeline:function(e){P(c.onMenuShareTimeline,{complete:function(){M("shareTimeline",{title:e.title||t,desc:e.title||t,img_url:e.imgUrl||"",link:e.link||location.href,type:e.type||"link",data_url:e.dataUrl||""},e)}},e)},onMenuShareAppMessage:function(n){P(c.onMenuShareAppMessage,{complete:function(e){"favorite"===e.scene?M("sendAppMessage",{title:n.title||t,desc:n.desc||"",link:n.link||location.href,img_url:n.imgUrl||"",type:n.type||"link",data_url:n.dataUrl||""}):M("sendAppMessage",{title:n.title||t,desc:n.desc||"",link:n.link||location.href,img_url:n.imgUrl||"",type:n.type||"link",data_url:n.dataUrl||""},n)}},n)},onMenuShareQQ:function(e){P(c.onMenuShareQQ,{complete:function(){M("shareQQ",{title:e.title||t,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},onMenuShareWeibo:function(e){P(c.onMenuShareWeibo,{complete:function(){M("shareWeiboApp",{title:e.title||t,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},onMenuShareQZone:function(e){P(c.onMenuShareQZone,{complete:function(){M("shareQZone",{title:e.title||t,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},updateTimelineShareData:function(e){M("updateTimelineShareData",{title:e.title,link:e.link,imgUrl:e.imgUrl},e)},updateAppMessageShareData:function(e){M("updateAppMessageShareData",{title:e.title,desc:e.desc,link:e.link,imgUrl:e.imgUrl},e)},startRecord:function(e){M("startRecord",{},e)},stopRecord:function(e){M("stopRecord",{},e)},onVoiceRecordEnd:function(e){P("onVoiceRecordEnd",e)},playVoice:function(e){M("playVoice",{localId:e.localId},e)},pauseVoice:function(e){M("pauseVoice",{localId:e.localId},e)},stopVoice:function(e){M("stopVoice",{localId:e.localId},e)},onVoicePlayEnd:function(e){P("onVoicePlayEnd",e)},uploadVoice:function(e){M("uploadVoice",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},downloadVoice:function(e){M("downloadVoice",{serverId:e.serverId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},translateVoice:function(e){M("translateVoice",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},chooseImage:function(e){M("chooseImage",{scene:"1|2",count:e.count||9,sizeType:e.sizeType||["original","compressed"],sourceType:e.sourceType||["album","camera"]},(e._complete=function(e){if(p){var n=e.localIds;try{n&&(e.localIds=JSON.parse(n))}catch(e){}}},e))},getLocation:function(e){},previewImage:function(e){M(c.previewImage,{current:e.current,urls:e.urls},e)},uploadImage:function(e){M("uploadImage",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},downloadImage:function(e){M("downloadImage",{serverId:e.serverId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},getLocalImgData:function(e){!1===I?(I=!0,M("getLocalImgData",{localId:e.localId},(e._complete=function(e){if(I=!1,0<_.length){var n=_.shift();wx.getLocalImgData(n)}},e))):_.push(e)},getNetworkType:function(e){M("getNetworkType",{},(e._complete=function(e){e=function(e){var n=e.errMsg;e.errMsg="getNetworkType:ok";var i=e.subtype;if(delete e.subtype,i)e.networkType=i;else{var t=n.indexOf(":"),o=n.substring(t+1);switch(o){case"wifi":case"edge":case"wwan":e.networkType=o;break;default:e.errMsg="getNetworkType:fail"}}return e}(e)},e))},openLocation:function(e){M("openLocation",{latitude:e.latitude,longitude:e.longitude,name:e.name||"",address:e.address||"",scale:e.scale||28,infoUrl:e.infoUrl||""},e)},getLocation:function(e){M(c.getLocation,{type:(e=e||{}).type||"wgs84"},(e._complete=function(e){delete e.type},e))},hideOptionMenu:function(e){M("hideOptionMenu",{},e)},showOptionMenu:function(e){M("showOptionMenu",{},e)},closeWindow:function(e){M("closeWindow",{},e=e||{})},hideMenuItems:function(e){M("hideMenuItems",{menuList:e.menuList},e)},showMenuItems:function(e){M("showMenuItems",{menuList:e.menuList},e)},hideAllNonBaseMenuItem:function(e){M("hideAllNonBaseMenuItem",{},e)},showAllNonBaseMenuItem:function(e){M("showAllNonBaseMenuItem",{},e)},scanQRCode:function(e){M("scanQRCode",{needResult:(e=e||{}).needResult||0,scanType:e.scanType||["qrCode","barCode"]},(e._complete=function(e){if(f){var n=e.resultStr;if(n){var i=JSON.parse(n);e.resultStr=i&&i.scan_code&&i.scan_code.scan_result}}},e))},openAddress:function(e){M(c.openAddress,{},(e._complete=function(e){e=function(e){return e.postalCode=e.addressPostalCode,delete e.addressPostalCode,e.provinceName=e.proviceFirstStageName,delete e.proviceFirstStageName,e.cityName=e.addressCitySecondStageName,delete e.addressCitySecondStageName,e.countryName=e.addressCountiesThirdStageName,delete e.addressCountiesThirdStageName,e.detailInfo=e.addressDetailInfo,delete e.addressDetailInfo,e}(e)},e))},openProductSpecificView:function(e){M(c.openProductSpecificView,{pid:e.productId,view_type:e.viewType||0,ext_info:e.extInfo},e)},addCard:function(e){for(var n=e.cardList,i=[],t=0,o=n.length;t<o;++t){var r=n[t],a={card_id:r.cardId,card_ext:r.cardExt};i.push(a)}M(c.addCard,{card_list:i},(e._complete=function(e){var n=e.card_list;if(n){for(var i=0,t=(n=JSON.parse(n)).length;i<t;++i){var o=n[i];o.cardId=o.card_id,o.cardExt=o.card_ext,o.isSuccess=!!o.is_succ,delete o.card_id,delete o.card_ext,delete o.is_succ}e.cardList=n,delete e.card_list}},e))},chooseCard:function(e){M("chooseCard",{app_id:v.appId,location_id:e.shopId||"",sign_type:e.signType||"SHA1",card_id:e.cardId||"",card_type:e.cardType||"",card_sign:e.cardSign,time_stamp:e.timestamp+"",nonce_str:e.nonceStr},(e._complete=function(e){e.cardList=e.choose_card_info,delete e.choose_card_info},e))},openCard:function(e){for(var n=e.cardList,i=[],t=0,o=n.length;t<o;++t){var r=n[t],a={card_id:r.cardId,code:r.code};i.push(a)}M(c.openCard,{card_list:i},e)},consumeAndShareCard:function(e){M(c.consumeAndShareCard,{consumedCardId:e.cardId,consumedCode:e.code},e)},chooseWXPay:function(e){M(c.chooseWXPay,V(e),e)},openEnterpriseRedPacket:function(e){M(c.openEnterpriseRedPacket,V(e),e)},startSearchBeacons:function(e){M(c.startSearchBeacons,{ticket:e.ticket},e)},stopSearchBeacons:function(e){M(c.stopSearchBeacons,{},e)},onSearchBeacons:function(e){P(c.onSearchBeacons,e)},openEnterpriseChat:function(e){M("openEnterpriseChat",{useridlist:e.userIds,chatname:e.groupName},e)},launchMiniProgram:function(e){M("launchMiniProgram",{targetAppId:e.targetAppId,path:function(e){if("string"==typeof e&&0<e.length){var n=e.split("?")[0],i=e.split("?")[1];return n+=".html",void 0!==i?n+"?"+i:n}}(e.path),envVersion:e.envVersion},e)},openBusinessView:function(e){M("openBusinessView",{businessType:e.businessType,queryString:e.queryString||"",envVersion:e.envVersion},(e._complete=function(n){if(p){var e=n.extraData;if(e)try{n.extraData=JSON.parse(e)}catch(e){n.extraData={}}}},e))},miniProgram:{navigateBack:function(e){e=e||{},O(function(){M("invokeMiniProgramAPI",{name:"navigateBack",arg:{delta:e.delta||1}},e)})},navigateTo:function(e){O(function(){M("invokeMiniProgramAPI",{name:"navigateTo",arg:{url:e.url}},e)})},redirectTo:function(e){O(function(){M("invokeMiniProgramAPI",{name:"redirectTo",arg:{url:e.url}},e)})},switchTab:function(e){O(function(){M("invokeMiniProgramAPI",{name:"switchTab",arg:{url:e.url}},e)})},reLaunch:function(e){O(function(){M("invokeMiniProgramAPI",{name:"reLaunch",arg:{url:e.url}},e)})},postMessage:function(e){O(function(){M("invokeMiniProgramAPI",{name:"postMessage",arg:e.data||{}},e)})},getEnv:function(e){O(function(){e({miniprogram:"miniprogram"===o.__wxjs_environment})})}}},T=1,k={};return i.addEventListener("error",function(e){if(!p){var n=e.target,i=n.tagName,t=n.src;if("IMG"==i||"VIDEO"==i||"AUDIO"==i||"SOURCE"==i)if(-1!=t.indexOf("wxlocalresource://")){e.preventDefault(),e.stopPropagation();var o=n["wx-id"];if(o||(o=T++,n["wx-id"]=o),k[o])return;k[o]=!0,wx.ready(function(){wx.getLocalImgData({localId:t,success:function(e){n.src=e.localData}})})}}},!0),i.addEventListener("load",function(e){if(!p){var n=e.target,i=n.tagName;n.src;if("IMG"==i||"VIDEO"==i||"AUDIO"==i||"SOURCE"==i){var t=n["wx-id"];t&&(k[t]=!1)}}},!0),e&&(o.wx=o.jWeixin=w),w}function M(n,e,i){o.WeixinJSBridge?WeixinJSBridge.invoke(n,x(e),function(e){A(n,e,i)}):B(n,i)}function P(n,i,t){o.WeixinJSBridge?WeixinJSBridge.on(n,function(e){t&&t.trigger&&t.trigger(e),A(n,e,i)}):B(n,t||i)}function x(e){return(e=e||{}).appId=v.appId,e.verifyAppId=v.appId,e.verifySignType="sha1",e.verifyTimestamp=v.timestamp+"",e.verifyNonceStr=v.nonceStr,e.verifySignature=v.signature,e}function V(e){return{timeStamp:e.timestamp+"",nonceStr:e.nonceStr,package:e.package,paySign:e.paySign,signType:e.signType||"SHA1"}}function A(e,n,i){"openEnterpriseChat"!=e&&"openBusinessView"!==e||(n.errCode=n.err_code),delete n.err_code,delete n.err_desc,delete n.err_detail;var t=n.errMsg;t||(t=n.err_msg,delete n.err_msg,t=function(e,n){var i=e,t=a[i];t&&(i=t);var o="ok";if(n){var r=n.indexOf(":");"confirm"==(o=n.substring(r+1))&&(o="ok"),"failed"==o&&(o="fail"),-1!=o.indexOf("failed_")&&(o=o.substring(7)),-1!=o.indexOf("fail_")&&(o=o.substring(5)),"access denied"!=(o=(o=o.replace(/_/g," ")).toLowerCase())&&"no permission to execute"!=o||(o="permission denied"),"config"==i&&"function not exist"==o&&(o="ok"),""==o&&(o="fail")}return n=i+":"+o}(e,t),n.errMsg=t),(i=i||{})._complete&&(i._complete(n),delete i._complete),t=n.errMsg||"",v.debug&&!i.isInnerInvoke&&alert(JSON.stringify(n));var o=t.indexOf(":");switch(t.substring(o+1)){case"ok":i.success&&i.success(n);break;case"cancel":i.cancel&&i.cancel(n);break;default:i.fail&&i.fail(n)}i.complete&&i.complete(n)}function C(e){if(e){for(var n=0,i=e.length;n<i;++n){var t=e[n],o=c[t];o&&(e[n]=o)}return e}}function B(e,n){if(!(!v.debug||n&&n.isInnerInvoke)){var i=a[e];i&&(e=i),n&&n._complete&&delete n._complete,console.log('"'+e+'",',n||"")}}function L(){return(new Date).getTime()}function O(e){l&&(o.WeixinJSBridge?e():i.addEventListener&&i.addEventListener("WeixinJSBridgeReady",e,!1))}});
\ No newline at end of file
{
"_from": "jweixin-module",
"_id": "jweixin-module@1.6.0",
"_inBundle": false,
"_integrity": "sha512-dGk9cf+ipipHmtzYmKZs5B2toX+p4hLyllGLF6xuC8t+B05oYxd8fYoaRz0T30U2n3RUv8a4iwvjhA+OcYz52w==",
"_location": "/jweixin-module",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "jweixin-module",
"name": "jweixin-module",
"escapedName": "jweixin-module",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/jweixin-module/-/jweixin-module-1.6.0.tgz",
"_shasum": "4a7ea614083e3c9c3f49e2fdc2bb882cfa58dfcd",
"_spec": "jweixin-module",
"_where": "D:\\diaoyun\\花园\\garden_merchant",
"author": {
"name": "Shengqiang Guo"
},
"bugs": {
"url": "https://github.com/zhetengbiji/jweixin-module/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "微信JS-SDK",
"devDependencies": {},
"homepage": "https://github.com/zhetengbiji/jweixin-module#readme",
"keywords": [
"wxjssdk",
"weixin",
"jweixin",
"wechat",
"jssdk",
"wx"
],
"license": "ISC",
"main": "lib/index.js",
"name": "jweixin-module",
"repository": {
"type": "git",
"url": "git+https://github.com/zhetengbiji/jweixin-module.git"
},
"scripts": {},
"version": "1.6.0"
}
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"jweixin-module": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/jweixin-module/-/jweixin-module-1.6.0.tgz",
"integrity": "sha512-dGk9cf+ipipHmtzYmKZs5B2toX+p4hLyllGLF6xuC8t+B05oYxd8fYoaRz0T30U2n3RUv8a4iwvjhA+OcYz52w=="
}
}
}
const erp = erp || {};
//const DOMAIN = 'https://dev.diaosaas.com/car/';
// const DOMAIN='https://diaosaas.com/car/'
// const DOMAIN='https://dev.diaosaas.com/partyHistory/'//测试
const DOMAIN='https://faces.diaosaas.com/garden/'//正式
// const DOMAIN = 'http://192.168.1.198:9095/';
//const DOMAIN = 'http://192.168.1.163:8089/';
//const DOMAIN ='http://47.110.68.2/car/'
//const HOST = '/api' + 'api/';
const HOST = DOMAIN + 'api/';
erp.login = HOST + 'wechat/login' //登录
erp.getOpenId = HOST + 'wechat/getOpenId' //微信授权获取openId
erp.number = HOST + 'user/number' //个人信息比赛次数
erp.addMatch = HOST + 'user/addMatch' //比赛提交数据
erp.getLearnAndMatch = HOST + 'subject/getLearnAndMatch' //获取题目
erp.rand = HOST + 'subject/rand' //获取排行榜
erp.myRand = HOST + 'user/rand' //获取个人排名
erp.sign = HOST + 'sign/list' //获取签名时间戳
export default erp;
const http = ({
url = '',
params = {},
...other
} = {}) => {
let time = Date.now()
return new Promise((resolve, reject) => {
let token = uni.getStorageSync("token");
uni.request({
url: url,
data: params,
header: {
'token': token,
'content-type': 'application/json' // 默认值
},
...other,
success: (res) => {
if (res.data.code == 500 && res.data.msg == '用户不存在') {
uni.showModal({
content: '登录已过期 请重新登录',
showCancel: false,
success(res) {
if (res.confirm) {
uni.reLaunch({
url: '/pages/login/login'
})
} else if (res.cancel) {
uni.reLaunch({
url: '/pages/login/login'
})
}
}
})
}
if (res.data.code == 402) {
uni.reLaunch({
url: '/pages/login/login'
})
}
if (res.data.code == 401 || res.data.code == 403) {
uni.showModal({
content: '登录已过期 请重新登录',
showCancel: false,
success(res) {
if (res.confirm) {
uni.reLaunch({
url: '/pages/login/login'
})
} else if (res.cancel) {
uni.reLaunch({
url: '/pages/login/login'
})
}
}
})
resolve(res.data)
}
if (res.data.code == 200) {
resolve(res.data)
} else {
resolve(res.data)
//uni.showToast({ title: '无法请求接口', icon: 'none', duration: 2000 })
reject(res)
}
},
fail: (err) => {
uni.hideLoading();
console.log(err)
}
})
})
}
module.exports = {
get(url, params = {}) {
return http({
url,
params
})
},
post(url, params = {}) {
return http({
url,
params,
header: {
"Content-Type": "application/json"
},
method: 'post'
})
},
apost(url, params = {}) {
return http({
url,
params,
header: {
"Content-Type": "application/json"
},
method: 'post'
})
},
put(url, params = {}) {
return http({
url,
params,
method: 'put'
})
},
// 这里不能使用 delete, delete为关键字段
myDelete(url, params = {}) {
return http({
url,
params,
method: 'delete'
})
},
/**
* 优惠券有效期
* startDate:起始日期
* valueTime:有效天数
*/
transferCouponValueTime(startDate, valueTime) {
var date = new Date(startDate);
var newDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + valueTime);
var year1 = date.getFullYear();
var month1 = date.getMonth() + 1;
var day1 = date.getDate();
var year2 = newDate.getFullYear();
var month2 = newDate.getMonth() + 1;
var day2 = newDate.getDate();
return year2 + "/" + month2 + "/" + day2
},
//获取时间
getDate(type) {
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
if (type === 'start') {
year = year - 60;
} else if (type === 'end') {
year = year + 2;
}
month = month > 9 ? month : '0' + month;;
day = day > 9 ? day : '0' + day;
return `${year}-${month}-${day}`;
},
// 转换为'00:00:00'
getDuration(my_time) {
if (my_time <= 0) {
return '0'
} else {
var days = my_time / 1000 / 60 / 60 / 24;
var daysRound = Math.floor(days);
var hours = my_time / 1000 / 60 / 60 - (24 * daysRound);
var hoursRound = Math.floor(hours) < 10 ? '0' + Math.floor(hours) : Math.floor(hours);
var minutes = my_time / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
var minutesRound = Math.floor(minutes) < 10 ? '0' + Math.floor(minutes) : Math.floor(minutes);
var seconds = my_time / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 *
minutesRound);
var secondsRound = Math.floor(seconds) < 10 ? '0' + Math.floor(seconds) : Math.floor(seconds)
// console.log('转换时间:', hoursRound + '时', minutesRound + '分', seconds + '秒');
// this.remaincutdown = hoursRound + ':' + minutesRound + ':' + seconds
var time = daysRound + '天' + hoursRound + ':' + minutesRound + ':' + secondsRound
return time
}
},
// 获取当前时间
getpresenttime() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
month >= 1 && month <= 9 ? (month = "0" + month) : "";
day >= 0 && day <= 9 ? (day = "0" + day) : "";
var timer = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return timer;
},
//获取当前往后十年list
getyearlist() {
var date = new Date()
var year = date.getFullYear()
let yearlist = []
for (var i = 0; i < 10; i++) {
let years = year + i
yearlist.push(years)
}
return yearlist
},
// 获取前后年份
getNearbyFiveears() {
let year = new Date().getFullYear()
let arr = []
for (var i = 0; i < 5; i++) {
let year1 = year - i + 1;
let year2 = year + i;
arr.push(year1)
arr.push(year2)
}
arr.sort((a, b) => {
return a - b
})
let yearArr = arr.map((item, index) => {
let obj = {}
obj.label = item
obj.value = index + 1
return obj
})
yearArr.unshift({
label: '全部',
value: 0
})
return yearArr
},
// 获取当前时间
getYearmomthday() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
month >= 1 && month <= 9 ? (month = "0" + month) : "";
day >= 0 && day <= 9 ? (day = "0" + day) : "";
var timer = year + '/' + month + '/' + day;
return timer;
},
//自定义加法运算
addNum(num1, num2) {
var sq1, sq2, m;
try {
sq1 = num1.toString().split(".")[1].length;
} catch (e) {
sq1 = 0;
}
try {
sq2 = num2.toString().split(".")[1].length;
} catch (e) {
sq2 = 0;
}
m = Math.pow(10, Math.max(sq1, sq2));
return (num1 * m + num2 * m) / m;
},
accMul(arg1, arg2) {
var m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length
} catch (e) {}
try {
m += s2.split(".")[1].length
} catch (e) {}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
},
}
async function compressImage(src, platform) {
const imageInfo = await getImageInfo(src);
const orientation = imageInfo.orientation;
let rotate = 0;
let quality = 80;
if (platform === 'ios') {
rotate = 0;
quality = 25;
} else {
switch (orientation) {
case 'up': //exif:1 不旋转
rotate = 0;
break;
case 'down': //exif:3 旋转180度
rotate = 180;
break;
case 'right': //exif:6 旋转90度
rotate = 90;
break;
case 'left': //exif:8 旋转270度
rotate = 270;
break;
default:
rotate = 0;
break;
}
}
return new Promise(function(resolve, reject) {
plus.zip.compressImage({
src: src,
dst: "_doc/uniapp_temp" + '/compressed/' + Math.round(new Date()) + '.jpg',
format: 'jpg',
quality: quality,
width: 'auto',
height: 'auto',
rotate: rotate,
},
function(event) {
let tempPath = event.target;
resolve(tempPath)
},
function(error) {
reject(error);
});
})
}
function getImageInfo(path) {
return new Promise(function(resolve, reject) {
// #ifdef APP-PLUS
plus.io.getImageInfo({
src: path,
success: function(image) {
// console.log(image.width);
// console.log(image.height);
// console.log('orientation=' + image.orientation);
// console.log('path=' + image.path);
resolve(image)
},
fail: function(err) {
console.log("getImageInfoErr: " + JSON.stringify(err));
reject(err)
}
});
// #endif
// #ifdef H5 || MP-WEIXIN
uni.getImageInfo({
src: path,
success: function(image) {
// console.log(image.width);
// console.log(image.height);
// console.log('orientation=' + image.orientation);
// console.log('path=' + image.path);
resolve(image)
},
fail: function(err) {
console.log("getImageInfoErr: " + JSON.stringify(err));
reject(err)
}
});
// #endif
});
}
export default compressImage
\ No newline at end of file
const get = (url, data, callBack) => {
uni.request({
url: url,
data: data,
method: 'GET',
header: {
'content-type': 'application/json;charset=utf-8' // 默认值
},
complete: function(res) {
callBack(res)
// console.log(res)
}
})
}
// 防抖
const antiShake = function antiSahake(fn) {
let timeId = null
console.log('防抖')
return function(fn) {
debugger
if (timeId) {
console.log('点击多次')
clearTimeout(timeId)
}
timeId = setTimeout(fn, 10000)
}
}
module.exports = {
get: get,
antiShake: antiShake,
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论