更新脚手架!

This commit is contained in:
Andy Leong
2023-12-29 18:41:59 +08:00
parent f1c3d10fd5
commit c0871a9b1f
29 changed files with 1004 additions and 149 deletions

31
src/plugins/Preloader.js Normal file
View File

@@ -0,0 +1,31 @@
// 图片资源预加载器
const imgPreloader = url => {
return new Promise((resolve, reject) => {
let image = new Image();
image.src = url;
image.onload = () => {
resolve();
};
image.onerror = () => {
reject();
};
});
};
const Preloader = ({ name, imgs, callback }) => {
let promiseArr = [];
let num = 0
imgs.forEach(element => {
promiseArr.push(imgPreloader(element).then((res => {
num++
let progress = parseInt((num / imgs.length) * 100)
callback(progress)
})));
});
console.log(name, promiseArr.length, '张');
return Promise.all(promiseArr);
};
export default Preloader

13
src/plugins/algorithm.js Normal file
View File

@@ -0,0 +1,13 @@
// 洗牌算法
export function FYShuffle(arr) {
let len = arr.length;
while (len > 1) {
let rand = Math.floor(Math.random() * len);
len--;
[arr[len], arr[rand]] = [arr[rand], arr[len]] // 采用的数组的结构赋值
}
return arr;
}

49
src/plugins/hooks.js Normal file
View File

@@ -0,0 +1,49 @@
import { ref } from 'vue'
// 倒计时
export function useCountDown() {
const countNum = ref(0)
const countInterval = ref(null)
const startCountDown = num => {
countNum.value = Number(num)
clearCountDown()
countInterval.value = setInterval(() => {
if (countNum.value === 0) {
clearInterval(countInterval.value)
countInterval.value = null
return
}
countNum.value--
}, 1000)
}
const clearCountDown = () => {
if (countInterval.value) {
clearInterval(countInterval.value)
}
}
return { countNum, startCountDown, clearCountDown }
}
// 防抖
export function useDebounce(cb, delay = 150) {
const timer = ref(null)
const handler = () => {
if (timer.value) {
clearTimeout(timer.value)
timer.value = setTimeout(() => {
cb()
}, delay)
} else {
timer.value = setTimeout(() => {
cb()
}, delay)
}
}
return { handler }
}

336
src/plugins/plugin.js Normal file
View File

@@ -0,0 +1,336 @@
// 常用的方法
import gsap from 'gsap'
const h5plugin = {
//是否在微信环境
isWX() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
},
// 判断是否移动端
isMobile() {
let userAgentInfo = navigator.userAgent;
let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
let getArr = Agents.filter(i => userAgentInfo.includes(i));
return getArr.length ? true : false;
},
// 判断微博环境
isWeibo() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/WeiBo/i) == "weibo") {
console.log("微博环境");
return true;
} else {
console.log("非微博环境");
return false;
}
},
// 判断Safari环境
isSafari() {
var ua = window.navigator.userAgent.toLowerCase();
if ((/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent))) {
console.log("Safari环境");
return true;
} else {
console.log("非Safari环境");
return false;
}
},
//是否为安卓
isAndriod() {
var naviga = navigator.userAgent;
if (naviga.indexOf('Android') > -1 || naviga.indexOf('Adr') > -1) {
console.log("Andriod环境");
return true;
} else {
console.log("非Andriod环境");
return false;
}
},
//路径获取关键字
getQueryString(name) {
//截取页面传递字符串
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
},
// 判断全面屏和非全面屏true为全面屏
judgeBigScreen() {
let result = false;
const rate = window.screen.height / window.screen.width;
let limit = window.screen.height == window.screen.availHeight ? 1.8 : 1.65; // 临界判断值
// window.screen.height为屏幕高度
// window.screen.availHeight 为浏览器 可用高度
if (rate > limit) {
// console.log("全面屏");
result = true;
return result;
}
// console.log("非面屏");
return result;
},
// 获取url html名称
getUrlHtml() {
//获取url地址
var ts_href = window.location.href;
var ts_mainText = "";
//获取地址最后一个“/”的下标
var ts_indexof = ts_href.lastIndexOf("/");
//获取地址“/”之后的的内容
var ts_indexText = ts_href.substring(ts_indexof + 1);
//获取地址“.html”的下标
var ts_htmlBeforeText = ts_indexText.indexOf(".html");
//获取 “/”到".html"之间的内容
ts_mainText = ts_indexText.substring(0, ts_htmlBeforeText);
console.log("当前入口:", ts_mainText);
return ts_mainText;
},
// 获取cookie中的值
getSetCookie(name, value, options) {
if (typeof value != 'undefined') {
options = options || {};
if (value === null) {
value = '';
options = this._extend({}, options, true);
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
// var cookie = $.trim(cookies[i]);
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) == name + '=') {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
},
// 安卓机型自动播放音乐
BGMAutoPlayMgr(url) {
this.audioContext = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
this.sourceNode = null;
this.buffer = null;
this.isPlayingBGM = false;
this.toggleBGM = function () {
if (typeof this.sourceNode == 'object') {
if (this.isPlayingBGM) {
this.sourceNode.stop();
this.isPlayingBGM = false;
} else this._playSourceNode();
}
}
this._playSourceNode = function () {
const audioContext = this.audioContext;
audioContext.resume();
const _sourceNode = audioContext.createBufferSource();
_sourceNode.buffer = this.buffer;
_sourceNode.loop = true;
_sourceNode.connect(audioContext.destination);
_sourceNode.start(0);
this.sourceNode = _sourceNode;
this.isPlayingBGM = true;
}
let loadAndAutoPlay = (audioUrl) => {
const audioContext = this.audioContext;
const xhr = new XMLHttpRequest();
xhr.open('GET', audioUrl, true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = () => {
if (xhr.status < 400 && xhr.status >= 200 && xhr.readyState === 4) {
audioContext.decodeAudioData(xhr.response, buffer => {
this.buffer = buffer;
WeixinJSBridge.invoke("getNetworkType", {}, () => this._playSourceNode());
});
}
}
xhr.send();
}
loadAndAutoPlay(url);
loadAndAutoPlay = null;
},
// 金管家获取openid及openToken
getJGJId() {
return new Promise(resolve => {
// 获取openid
PALifeOpen.getOpenId(
{
appId: '1aeedce2a31340e591a5d64080d6105b' // 商户编号,区分⽣产和测试环境商户编号
},
rsp => {
// 调⽤接⼝成功后的回调函数
console.log('success', rsp.data);
store.state.openId = rsp.data.openId
store.state.openToken = rsp.data.openToken
if (rsp.ret == 0) {
store.state.openId = rsp.data.openId
store.state.openToken = rsp.data.openToken
const data = {
id: store.state.openId,
token: store.state.openToken
};
resolve(data);
// console.log(`获取到金管家openid时间${Math.abs(s_t - new Date().getTime())}`);
}
if (rsp.ret == -1) {
console.log(JSON.stringify(rsp));
}
},
e => {
// 调⽤接⼝异常的回调函数
console.log('failed', e);
}
)
})
},
// 金管家内部埋点
addPoint(page, spage, des = {}) {
const activityId = process.env.VUE_APP_ACTIVITYID;
PALifeOpen.invoke(
"device",
"addRecord",
{
eventId: `499${page}-${activityId}`, //必填,根据需求
labelId: `499${page}${spage}-${activityId}`, //必填,根据需求
// 扩展参数
parameters: {
ext: JSON.stringify(des)
}
},
// 调用接口成功后的回调函数 // alert(JSON.stringify(rsp))
rsp => console.debug("success ", rsp),
// 调用接口异常的回调函数
e => console.debug("failed ", e),
{
timeout: 86400000
}
);
return this;
},
// 百度统计埋点
addPointByBd(des) {
_hmt && _hmt.push(["_trackEvent", `${des}`, `${des} success`]);
return this;
},
// 防抖函数
debounceTap(fn, wait) {
let timer
return (...args) => {
// @ts-ignore
const context = this
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
timer = null
fn.apply(context, args)
}, wait)
}
},
// 节流函数
throttle(fn, wait) {
let inThrottle = false
return (...args) => {
// @ts-ignore
const context = this
if (!inThrottle) {
inThrottle = true
fn.apply(context, args)
setTimeout(() => {
inThrottle = false
}, wait)
}
}
},
// vite环境引用图片
imgUrl(url) {
return new URL(`../assets/images/${url}`, import.meta.url).href
},
// 计算两个日期之间的天数(开始日期,结束日期)
getDaysBetween(date1, date2) {
let day1 = new Date(date1.join('-'))
let day2 = new Date(date2.join('-'))
let oneDay = 24 * 60 * 60 * 1000;
let diffDays = Math.round(Math.abs((day2 - day1) / oneDay));
return diffDays;
},
// 计算星座
getAstro(month, day) {
var s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
return s.substr(month * 2 - (day < arr[month - 1] ? 2 : 0), 2);
},
// 引入BGM
createBGM() {
var bgmElement = document.createElement('div');
// document.querySelector('app').appendChild(bgmElement)
// <div class="music_icon" @click="musicPlay">
// <audio style="display: none; height: 0" id="bg-music" autoplay="autoplay" preload="auto" :src="audioUrl"
// loop="loop"></audio>
// </div>
}
}
export default h5plugin;

69
src/plugins/wxshare.js Normal file
View File

@@ -0,0 +1,69 @@
import wx from 'weixin-js-sdk';
import axios from "axios";
import { Toast } from "vant";
const imgUrl = new URL(`../assets/images/share.jpg`, import.meta.url).href
const linkUrl = import.meta.env.VITE_HOST + import.meta.env.VITE_FOLDER
export function wxShare(option) {
let url = location.href.split('#')[0];
// qiween: https://www.qiween.com/wxapi/api/jsconfig
// 信蜂: https://wx.xfhd.net/wxapi/api/jsconfig?appid=wx41d80a1bb01f658d
axios.get('https://wx.xfhd.net/wxapi/api/jsconfig?appid=wx41d80a1bb01f658d', {
params: { url }
})
.then((res) => {
console.log('分享配置:', {
'title': option.title,
'desc': option.desc,
'link': linkUrl + option.link
});
let data = res.data;
wx.config({
debug: false, // 开启调试模式
appId: data.appId, // 必填,公众号的唯一标识
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature, // 必填签名见附录1
jsApiList: [
'checkJsApi',
'chooseImage',
'closeWindow',
'chooseWXPay',
'scanQRCode',
'showMenuItems',
'onMenuShareAppMessage',
'onMenuShareTimeline',
] // 必填需要使用的JS接口列表所有JS接口列表见附录2
})
wx.ready(function () {
wx.hideMenuItems({
menuList: ["menuItem:copyUrl", "menuItem:share:appMessage", "menuItem:share:timeline"] // 屏蔽复制链接
});
wx.onMenuShareTimeline({
link: linkUrl + option.link, // 分享链接
title: option.title, // 分享标题
desc: option.desc, // 分享描述
imgUrl: imgUrl, // 分享图标
success() {// 用户成功分享后执行的回调函数
Toast('分享成功')
},
});
wx.onMenuShareAppMessage({
link: linkUrl + option.link, // 分享链接
title: option.title, // 分享标题
desc: option.desc, // 分享描述
imgUrl: imgUrl, // 分享图标
success() {// 用户成功分享后执行的回调函数
Toast('分享成功')
},
})
})
})
.catch(() => {
});
}