防抖方法
/**
* 防抖
* @param {Function} func 要执行的回调函数
* @param {Number} wait 延时的时间
* @param {Boolean} immediate 是否立即执行
* @return null
*/
let timeout;
export default function Debounce(func, wait = 3000, immediate = true) {
// 清除定时器
if (timeout !== null) clearTimeout(timeout);
// 立即执行,此类情况一般用不到
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(function() {
timeout = null;
}, wait);
if (callNow) typeof func === 'function' && func();
} else {
// 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
timeout = setTimeout(function() {
typeof func === 'function' && func();
}, wait);
}
}
Debounce(()=>{
console.log(1);
});
函数只执行一次
function once (fn){
let called = false
return function () {
if (!called) {
called = true
fn.apply(this, arguments)
}
}
}
function func (){
console.log(1);
}
//调用闭包函数
let onlyOnce = once(func);
onlyOnce(); // 1
onlyOnce();
用 apply 将数组各项添加到另一个数组
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
微信JS-SDK 调用
import wx from 'weixin-js-sdk' //引入微信js-sdk
import { getWXSignature } from '../request/api'
const custom = function(url, jsApiList) {
return getWXConfig(url, jsApiList)
}
function getWXConfig(url, jsApiList) {
getWXSignature({ url })
.then(res => {
let { appId, timestamp, noncestr, signature } = res.data
console.log(appId, timestamp, noncestr, signature, jsApiList, url)
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: appId, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: noncestr, // 必填,生成签名的随机串
signature: signature, // 必填,签名
jsApiList: jsApiList, // 必填,需要使用的JS接口列表
})
wx.error(function(res) {
console.log('wxerr', res)
})
})
.catch(err => {
console.log(err)
})
}
export default custom
// ***
getWeiXinConfig() {
let url = window.location.href
// let url = encodeURIComponent(location.href.split('#')[0])
this.$getWXConfig(url, ['scanQRCode'])
}
//微信扫一扫
wxSweep() {
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ['barCode'], //'qrCode', 可以指定扫二维码还是一维码,默认二者都有
success: function(res) {
var result = res.resultStr // 当needResult 为 1 时,扫码返回的结果
console.log(result)
if (this.type === 1) {
//位置上传
this.$router.push({
path: '/updateLocation',
query: {
projectId: this.projectId,
type: 1,
mac: result,
},
})
} else if (this.type === 2) {
//模块更换
this.$router.push({
path: '/changeModule',
query: {
projectId: this.projectId,
type: 1,
mac: result,
},
})
} else {
//开关更换
this.$router.push({
path: '/changeSwitch',
query: {
projectId: this.projectId,
type: 1,
mac: result,
},
})
}
},
})
},
js 递归数组降维
let children = [1, [2, 3], [4, [5, 6, [7, 8]]], [9, 10]];
function simpleNormalizeChildren(children) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
children = Array.prototype.concat.apply([], children);
simpleNormalizeChildren(children)
}
}
return children;
}
console.log(simpleNormalizeChildren(children));
simpleNormalizeChildren(children); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
js 数组降维(二维降一维)
function simpleNormalizeChildren(children) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
let arrs = [
[
'1'
],
[
'3'
]
];
const arr = simpleNormalizeChildren(arrs);
console.log(arr); // ['1','3']
File对象 转 base64
inputImage(e) {
let img = e.target.files[0];
if (img) {
this.blobToDataURL(img);
}
},
blobToDataURL(blob) {
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function(evt) {
let base64 = evt.target.result;
console.log(base64);
};
},
检测数据对象中是否有空对象
let arr = [{},{name:'1'}]
const arr = this.bannerList.filter(item =>
item == null || item == '' || JSON.stringify(item) == '{}'
);
console.log(arr.length > 0 ? '不通过' : '通过')
input 数字类型
<el-input
v-model.number="form.redVal"
type="number"
@keydown.native="channelInputLimit"
placeholder="请输入阈值设定"
maxlength="8"
></el-input>
channelInputLimit(e) {
let key = e.key;
// 不允许输入‘e‘和‘.‘
if (key === 'e' || key === '.') {
e.returnValue = false;
return false;
}
return true;
},
格式化时间
/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string | null}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0 || !time) {
return null;
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
let date;
if (typeof time === 'object') {
date = time;
} else {
if (typeof time === 'string') {
if (/^[0-9]+$/.test(time)) {
// support "1548221490638"
time = parseInt(time);
} else {
// support safari
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
time = time.replace(new RegExp(/-/gm), '/');
}
}
if (typeof time === 'number' && time.toString().length === 10) {
time = time * 1000;
}
date = new Date(time);
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
};
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key];
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value];
}
return value.toString().padStart(2, '0');
});
return time_str;
}
循环判断值是否一样
// 循环判断值是否一样
function isObjectValueEqual(a, b) {
//取对象a和b的属性名
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
//判断属性名的length是否一致
if (aProps.length != bProps.length) {
return false;
}
//循环取出属性名,再判断属性值是否一致
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
export default isObjectValueEqual;