1.时间格式化(yyyy-mm--dd hh:mm:ss)
//时间格式化
export function formatTime(value, type, string = '-') {
if (!value) {
return '--';
}
let dataTime = "";
let data = new Date(Number(value));
let year = data.getFullYear();
let month = data.getMonth() + 1 > 9 ? data.getMonth() + 1 : '0' + (data.getMonth() + 1);
let day = data.getDate() > 9 ? data.getDate() : '0' + data.getDate();
let hour = data.getHours() > 9 ? data.getHours() : '0' + data.getHours();
let minute = data.getMinutes() > 9 ? data.getMinutes() : '0' + data.getMinutes();
let second = data.getSeconds() > 9 ? data.getSeconds() : '0' + data.getSeconds();
switch (type) {
case "YMD":
dataTime = year + string + month + string + day;
break;
case "HMS":
dataTime = hour + ":" + minute + ":" + second;
break;
case "YM":
dataTime = year + string + month;
break;
case "MD":
dataTime = month + string + day;
break;
case "YMD hh:mm":
dataTime = year + string + month + string + day + " " + hour + ":" + minute;
break;
default:
dataTime = year + string + month + string + day + " " + hour + ":" + minute + ":" + second;
}
return dataTime;//将格式化后的字符串输出到前端显示
}
2.数据去重且保留最新的数据及多参数排序
/**
* 去重 reducer 函数接收4个参数:
* @param {Array} acc 累计器
* @param {Object} cur 当前值
* @param {Number} index 当前索引
* @returns {Array} srcArray 源数组
*/
export function arrayUnique2(arr, name) {
var hash = {};
return arr.reduce(function (acc, cru,index) {
if (!hash[cru[name]]) {
hash[cru[name]] = {index:index}
acc.push(cru)
}else{
acc.splice(hash[cru[name]]['index'],1,cru)
}
return acc;
}, []);
}
使用:
//dataArr 数组 , orderNo 数组合并去重 关键字
let datalistNew = arrayUnique2(dataArr, 'orderNo');
// 双参数 排序
datalistNew.sort((a,b)=>{return a.startTime ===b.startTime? b.endTime - a.endTime: b.startTime-a.startTime });
3.防抖
/**
* 防反跳。fn函数在最后一次调用时刻的delay毫秒之后执行!
* @param fn 执行函数
* @param delay 时间间隔
* @param isImmediate 为true,debounce会在delay时间间隔的开始时立即调用这个函数
* @returns {Function}
*/
function debounce(fn, delay, isImmediate) {
var timer = null; //初始化timer,作为计时清除依据
return function() {
var context = this; //获取函数所在作用域this
var args = arguments; //取得传入参数
clearTimeout(timer);
if(isImmediate && timer === null) {
//时间间隔外立即执行
fn.apply(context,args);
timer = 0;
return;
}
timer = setTimeout(function() {
fn.apply(context,args);
timer = null;
}, delay);
}
}
export default {
debounce,
}
4. 字符串组装例如处理蓝牙分包
1.蓝牙数据16进制的规则:首帧, 帧长度,及帧尾,三个关键字组转完整 满足条件的16进制数据 供业务页面使用。
let cache = '';
function checkComplete(str) {
const length = parseInt(str.substring(2, 4), 16);
return str.startsWith('55') && str.endsWith('16') && str.length === length*2 + 8;
}
export function watchNotify(str) {
let complete = checkComplete(str);
if (complete && !cache) {
return str;
}
if((!cache && str.startsWith('55')) || cache.startsWith('55')){
cache += str;
}
complete = checkComplete(cache);
if (complete) {
const res = cache;
cache = '';
return res;
}
}
export function setCache(val){
cache = val
}
5.加密传输,及解密
import CryptoJS from 'crypto-js'; //引用AES源码js
const key = CryptoJS.enc.Hex.parse("密钥"); //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Hex.parse('密钥'); //十六位十六进制数作为密钥偏移量
//解密方法
function Decrypt(word) {
if(word) {
let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
let decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
// let decrypt = CryptoJS.AES.decrypt(srcs, key, { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
} else {
return ''
}
}
//加密方法
function Encrypt(word) {
// let srcs = CryptoJS.enc.Hex.parse(word);
let encrypted = CryptoJS.AES.encrypt(word, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
// let encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
return encrypted.ciphertext.toString().toUpperCase();
}
export default {
Decrypt,
Encrypt
};
6.蓝牙数据流及16进制10进制数据转化相互处理
/**
* 字符串转16进制
* @typedef {object} json
* @property {DataView} dataView
* @property {String} string
* @property {Number} byteOffset
*/
function string2HexFromDataView({ dataView, string, byteOffset = 0 }) {
// string : 1681972230297
for (let i = 0; i < string.length; i++) {
const idx = i + byteOffset;
// console.log(string[i].charCodeAt(0).toString(16))
dataView.setUint8(idx, '0x' + string[i].charCodeAt(0).toString(16))
}
}
/**
* 数值(10进制)转16进制buffer 为了容 时间戳
*/
function number2HexForDataView({ dataView, number, byteOffset = 0 }) {
const hex = number.toString(16);
for (let i = 0; i < hex.length; i+=2) {
const idx = i / 2 + byteOffset;
dataView.setUint8(idx, '0x' + hex.substr(i, 2))
}
}
/**
* 检验和
* @param {DataView} dataView
* @param {Number} start
* @param {Number} end
* @returns Hex
*/
function checkSum(dataView, start, end) {
let sum = 0;
for (let i = start; i <= end; i++) {
const view = dataView.getUint8(i);
sum += view;
}
// console.log('ss', sum)
// return (('0x' + sum.toString(16)) & 0xFF).toString(16); // 与运算取8位
const resHex = (('0x' + sum.toString(16)) & 0xFF).toString(16);
return resHex.length === 1? 0+''+ resHex: resHex;
}
/**
* 命令帧
* @typedef {object} json
* @property {Hex} head
* @property {Hex} end
* @property {Number} length
* @property {Hex} command
* @property {String|Number} code
* @returns ArrayBuffer
*/
function $command_tobuffer({ head = 0x55, end = 0x16, length, command, body, type='default' }) {
const byteOffset = 3; // 帧头 + 帧长度 + 命令
const buffer = new ArrayBuffer(byteOffset + length + 1); // byteOffset - 1 + length + 校验值 + 帧尾
const dataView = new DataView(buffer);
dataView.setUint8(0, head); // 帧头
dataView.setUint8(1, '0x' + length.toString(16)); // 帧长
dataView.setUint8(2, command); // 命令字
// 主体信息
if(type==='default'){
string2HexFromDataView({
dataView,
string: body,
byteOffset
});
} else {
number2HexForDataView({
dataView,
number: body,
byteOffset
});
}
const checkCodeIdx = length + 2;
const sign = checkSum(dataView, 2, checkCodeIdx);
// console.log('sum', sign);
dataView.setUint8(checkCodeIdx, '0x' + sign); // 检验码
dataView.setUint8(checkCodeIdx + 1, end); // 帧尾
return {buffer, checkSum:sign};
}
// const result = $command_tobuffer({
// body: 'J230209001',
// length: 11,
// command: 0xAB,
// })
// console.log(result)
/**
* 16进制转换成字符串
* @param {Hex} hex
* @returns String
*/
function $command_parsehex(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2) {
var v = parseInt(hex.substr(i, 2), 16);
if (v) str += String.fromCharCode(v);
}
return str;
}
/**
* 转化进制并比补位
* @param {Number} val
* @param {Number} radix
* @param {*} length
* @returns String
*/
function toStringPad(val, radix = 10, length = 2) {
return val.toString(radix).padStart(length, 0);
}
function $command_parsebuffer(buffer) {
const dataView = new DataView(buffer);
const head = toStringPad(dataView.getUint8(0), 16);
const length = dataView.getUint8(1);
const command = toStringPad(dataView.getUint8(2), 16);
const end = toStringPad(dataView.getUint8(length + 3), 16);
const sign = toStringPad(dataView.getUint8(length + 2), 16);
const byteOffset = 3;
let body = '';
for (let i = 0; i < length - 1; i++) {
const view = toStringPad(dataView.getUint8(i + byteOffset), 16);
body += view;
}
return {
head,
length: toStringPad(length, 16),
command,
body,
sign,
end,
};
}
// const val = parse(result);
// console.log(hex2a(val.body))
function $command_splithex(hex, paramsArr) {
let resObj = {};
paramsArr.map((item)=> resObj[item.key] = hex.substr(item.start, item.len))
return resObj;
}
function $command_hexTobuffer(HexStr) {
const buffer = new ArrayBuffer(HexStr.length/2);
const dataView = new DataView(buffer);
for (let i = 0; i < HexStr.length; i+=2) {
const idx = i / 2;
dataView.setUint8(idx, '0x' + HexStr.substr(i, 2))
}
return buffer;
}
export {
$command_tobuffer, // 将字符转化为buffer
$command_parsebuffer, // 解析业务buffer
$command_parsehex, // 16进制转化字符
$command_splithex, // 16进制数据使用业务处理
checkSum,
$command_hexTobuffer, // 将16进制转成buffer
}
7.代码风格好看版 时间格式化 (kdh写的)
// 日期时间格式化
Date.prototype.format = function (t) {
if(!this)return;
let arr = {
'y+': this.getFullYear(),//年
'M+': this.getMonth() + 1,//月份
'd+': this.getDate(),//日
'h+': this.getHours(),//小时
'm+': this.getMinutes(),//分
's+': this.getSeconds(),//秒
'q+': Math.floor((this.getMonth() + 3) / 3),//季度
'w+': this.getDay(), //星期
'S+': this.getMilliseconds()//毫秒
};
let d = t || 'yyyy-MM-dd hh:mm:ss';
for (let i in arr) {
if (new RegExp('(' + i + ')').test(d)) {
let s = '' + arr[i], n = RegExp.$1.length - s.length;
d = d.replace(RegExp.$1, n > 0 ? new Array(n + 1).join('0') + s : s);
}
}
return d;
};
//列表中格式化日期时间
let dateFormatter = (row, column, cellValue, index)=> {
if(cellValue){
return new Date(cellValue).format();
}else{
return "-";
}
}
使用实例:
<el-table-column
align="center"
:formatter="dateFormatter"
prop="createTime"
label="创建时间">
</el-table-column>
8.格式化银行卡号
/**
* 格式化银行卡号
* 目前规则为 4个字符加一个空格
*
* @param bankCardCode 银行卡号
*/
function fomartBankCardCode(bankCardCode){
//遍历账户
let spaceStr = "";
for (let i = 0, len = bankCardCode.length; i < len; i++) {
//每4个字符加一个空格
if (i % 4 === 0) {
spaceStr += " " + bankCardCode[i];
} else {
spaceStr += bankCardCode[i];
}
}
return spaceStr;
}
9.数据isNull
function isNil(val){
if(val === '' || val === null || val === undefined){
return true
}
return false
}
10.获取游览器cookie
function getCookie(name) {
var cookies = document.cookie.split("; ");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].split("=");
if (cookie[0] == name) {
return cookie[1];
}
}
return "";
}
11.保留三位小数
toFixedNum(val) {
return (val||val==0)?parseFloat(val).toFixed(3):'--';
}