最近项目用到了的一个比较常用封装的公共方法,记录一下:
import Config from '@/../config.js';
import wx from 'weixin-js-sdk';
import http from '@/http';
const PROJECT_NAME = Config.data.name;
// 设置localstorage
export function setLocalStorage(key, value) {
return localStorage.setItem(PROJECT_NAME + '-' + key, JSON.stringify(value))
}
// 获取localstorage
export function getLocalStorage(key) {
let json = localStorage.getItem(PROJECT_NAME + '-' + key)
if (!json || json == 'undefined') {
return '';
}
return JSON.parse(json)
}
// 删除localstorage
export function removeLocalStorage(key) {
return localStorage.removeItem(PROJECT_NAME + '-' + key)
}
// 获取参数
export function getParmas(url) {
var theRequest = {},
strs;
if (url.indexOf('?') != -1) {
var str = url.split('?')[1];
strs = str.split("&");
for (var i = strs.length - 1; i >= 0; i--) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest;
}
// 获取设备
export function getDevice() {
var agent = navigator.userAgent.toLowerCase();
var device = {};
if (agent.match(/MicroMessenger/i) == "micromessenger") {
device.app = 'weixin'; //在微信中打开
} else if (agent.match(/QQ\//i) == "qq/") {
device.app = 'qq'; //在QQ打开
} else if (agent.match(/WeiBo/i) == "weibo") {
device.app = 'weibo'; //在新浪微博客户端打开
}
if (agent.indexOf('android') != -1) {
device.platform = 'Android';
} else if (agent.indexOf('iphone') != -1) {
device.platform = 'iOS';
}
return device;
}
//判断是移动端还是pc端
export function getplatform() {
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
return 'mobile';
} else {
return 'pc';
}
}
/**
* 对Date的扩展,将 Date 转化为指定格式的String
* @param {number} dt
* @param {string} fmt
*/
export function dateformatFilter(dt, fmt = 'yyyy-MM-dd hh:mm:ss') {
if (!dt || dt == '' || dt == 0) {
return '';
}
dt = new Date(+dt);
var o = {
"M+": dt.getMonth() + 1,
"d+": dt.getDate(),
"h+": dt.getHours() % 12 == 0 ? 12 : dt.getHours() % 12,
"H+": dt.getHours(),
"m+": dt.getMinutes(),
"s+": dt.getSeconds(),
"q+": Math.floor((dt.getMonth() + 3) / 3),
"S": dt.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (dt.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var 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;
}
//js 时间戳转换成几分钟前,几小时前,几天前
export function formatMsgTime (timespan) {
var dateTime = new Date(timespan);
var year = dateTime.getFullYear();
var month = dateTime.getMonth() + 1;
var day = dateTime.getDate();
var hour = dateTime.getHours();
var minute = dateTime.getMinutes();
var second = dateTime.getSeconds();
var now = new Date();
var now_new = Date.parse(now.toDateString()); //typescript转换写法
var milliseconds = 0;
var timeSpanStr;
milliseconds = now_new - timespan;
if (milliseconds <= 1000 * 60 * 1) {
timeSpanStr = '刚刚';
}
else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
}
else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
}
else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
}
else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) {
timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute;
} else {
timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
}
return timeSpanStr;
};
//js 时间戳转换成时长
export function setHour(start,end){
var t,s = (Number(end) - Number(start))/1000;
if(s > -1){
var hour = Math.floor(s/3600);
var min = Math.floor(s/60) % 60;
var sec = s % 60;
var day = parseInt(hour / 24);
if (day > 0) {
hour = hour - 24 * day;
t = day + "day " + hour + ":";
}
else t = hour + ":";
if(min < 10){t += "0";}
t += min + ":";
if(sec < 10){t += "0";}
t += sec.toFixed(2);
}
return t;
}
//微信浏览器禁止页面下拉查看网址(不影响页面内部scroll)
export function overScroll (className) {
var overscroll = function(el) {
el.addEventListener('touchstart', function() {
var top = el.scrollTop
, totalScroll = el.scrollHeight
, currentScroll = top + el.offsetHeight;
if(top === 0) {
el.scrollTop = 1;
} else if(currentScroll === totalScroll) {
el.scrollTop = top - 1;
}
});
el.addEventListener('touchmove', function(evt) {
if(el.offsetHeight < el.scrollHeight)
evt._isScroller = true;
});
}
overscroll(document.querySelector(className));
document.body.addEventListener('touchmove', function(evt) {
if(!evt._isScroller) {
evt.preventDefault();
}
})
}
// 根据 appid 请求用户 code (非开发者模式使用, 静默授权)
export function getUserCode(config) {
if (!config) {
console.warn('缺少参数: config');
return null;
};
if (!config.state) {
console.warn('缺少参数: state');
return null;
};
if (!config.appId) {
console.warn('缺少参数: appId');
return null;
};
var scope='snsapi_userinfo';
if(config.oauthType){
scope=config.oauthType;
}
// 编码转换 decodeURIComponent(striing)解析
config.stateCode = encodeURIComponent(config.state);
if(config.stateCode.length > 128){
console.warn('state 过长(只允许长度为128字节)');
return null;
}
config.redirect_uri = window.location.protocol + '//' + window.location.host + window.location.pathname + '#/' + config.state;
config.redirect_uri = encodeURIComponent(config.redirect_uri);
debugger
var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.appId +
'&redirect_uri=' + config.redirect_uri +
'&response_type=code&scope='+scope+'&state=' + config.stateCode + '#wechat_redirect';
window.location.href = url;
}
//微信 jssdk-----------------------------------
function weixin_config(config,_data){
// 微信配置
wx.config({
debug: config.debug || false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: config.appId, // 必填,公众号的唯一标识
timestamp: config.timestamp, // 必填,生成签名的时间戳
nonceStr: config.nonceStr, // 必填,生成签名的随机串
signature: config.signature, // 必填,签名,见附录1
jsApiList: [
'openEnterpriseChat',
'openEnterpriseContact',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
'startRecord',
'stopRecord',
'onVoiceRecordEnd',
'playVoice',
'pauseVoice',
'stopVoice',
'onVoicePlayEnd',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'translateVoice',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'closeWindow',
'scanQRCode'
]
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function() {
setTimeout(function(){
wx.hideMenuItems({
menuList: [
'menuItem:copyUrl',
'menuItem:openWithSafari',
'menuItem:openWithQQBrowser',
'menuItem:originPage',
'menuItem:share:brand',
'menuItem:share:qq',
'menuItem:share:weiboApp',
'menuItem:share:facebook',
'menuItem:share:QZone',
] // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3
});
var shareData = {
title: _data.title ||'', // 分享标题
desc: _data.desc ||'', // 分享描述
link: _data.link ||'', // 分享链接
imgUrl: _data.imgUrl ||'', // 分享图标
type: 'link', // 分享类型,music、video或link,不填默认为link
dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
};
wx.onMenuShareTimeline(shareData);
wx.onMenuShareAppMessage(shareData);
},50);
});
wx.error(function(res){
console.warn('微信初始化失败');
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});
}
export function weixin_getConfig(_data) {
var _href = window.location.href.split('#')[0];
http({
url: '/wx/circle/nologin/getConfig?url=' + encodeURIComponent(_href),
method: 'get',
}).then(rpn=>{
if(rpn.success){
weixin_config(rpn.data,_data);
//console.log('统计成功');
}else{
if(rpn.resultMsg){
alert(rpn.resultMsg);
}else{
alert('服务器繁忙,请稍后再试!');
}
}
})
}