常用js公共函数集

import { Button, message , modal } from 'ant-design-vue';

import { settlementStatusList,payTypeList } from '@/utils/state'

 

export function timeFix() {

const time = new Date()

const hour = time.getHours()

return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'

}

 

/**

* 触发 window.resize

*/

export function triggerWindowResizeEvent() {

const event = document.createEvent('HTMLEvents')

event.initEvent('resize', true, true)

event.eventType = 'message'

window.dispatchEvent(event)

}

 

export function handleScrollHeader(callback) {

let timer = 0

 

let beforeScrollTop = window.pageYOffset

callback = callback || function () { }

window.addEventListener(

'scroll',

event => {

clearTimeout(timer)

timer = setTimeout(() => {

let direction = 'up'

const afterScrollTop = window.pageYOffset

const delta = afterScrollTop - beforeScrollTop

if (delta === 0) {

return false

}

direction = delta > 0 ? 'down' : 'up'

callback(direction)

beforeScrollTop = afterScrollTop

}, 50)

},

false

)

}

//检测ie

export function isIE() {

const bw = window.navigator.userAgent

const compare = (s) => bw.indexOf(s) >= 0

const ie11 = (() => 'ActiveXObject' in window)()

return compare('MSIE') || ie11

}

 

export function removeLoadingAnimate(id = '', timeout = 1500) {

if (id === '') {

return

}

setTimeout(() => {

document.body.removeChild(document.getElementById(id))

}, timeout)

}

 

 

//对象转formdata格式

export function objToFormData(config) {

let formData = new FormData();

let obj = config.data;

let arrayKey = config.arrayKey;

for (var i in obj) {

if (Array.isArray((obj[i]))) {

obj[i].map(item => {

if (!arrayKey) {

formData.append(i, item)

} else {

formData.append(i + '[]', item)

}

})

} else {

formData.append(i, obj[i])

}

}

return formData;

}

 

/获取时间yydd

export const getDateFormat = (date) => {

var y = date.getFullYear();

var m = date.getMonth() + 1;

m = m < 10 ? ('0' + m) : m;

var d = date.getDate();

d = d < 10 ? ('0' + d) : d;

var h = date.getHours();

h = h < 10 ? ('0' + h) : h;

var minute = date.getMinutes();

var second = date.getSeconds();

minute = minute < 10 ? ('0' + minute) : minute;

second = second < 10 ? ('0' + second) : second;

return {

'ymd': y + '-' + m + '-' + d,

'ymdhm': y + '-' + m + '-' + d + ' ' + h + ':' + minute,

}

}

 

//获取html字符串中的内容 编辑器内容

export const htmlToText = (data) => {

return data.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '').replace(/<[^>]+?>/g, '').replace(/\s+/g, ' ').replace(/ /g, ' ').replace(/>/g, ' ');

}

//去掉对象中属性为空的属性 0要特殊处理 默认为false

export const getObjNotEmptyAttr = (afferentObj = {}) => {

let carTypeAllQuery = {};

Object.keys(afferentObj).forEach((item) => {

if (afferentObj[item] !== null && afferentObj[item] !== undefined && afferentObj[item] !== '' && afferentObj[item] !==false) {

console.log(item,'item')

carTypeAllQuery[item] = afferentObj[item]

}

})

return carTypeAllQuery

}

 

//数组去重

export const getArrDuplicate = (arr = []) => {

let getArr = new Set(arr)

return Array.from(getArr);

}

 

/删除数组指定下标元素

export const deleteArrIndex = (arr = [], index, num) => {

// let getArr = new Set(arr)

let newArr = arr;

newArr.splice(index, num);

return newArr;

}

 

//邮箱校验

export function isEmail(s) {

return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)

}

 

//手机号校验

export function isMobile(mobile) {

// var index1 = mobile.substring(0, 1);

// var index2 = mobile.substring(0, 2);

// if (index2 == '11' || index2 == '12' || index1 !== '1' || mobile.length !== 11) {

// return false;

// } else {

// return true;

// }

let getMobile = parseInt(getMobile);

if (7 <= getMobile.length <= 13) {

return true

} else {

return false

}

}

 


/数组校验

export function isArray(arr) {

return Array.isArray(arr);

}

//截取地址 isCutoutAddress('', '/')

export function isCutoutAddress(str, mark) {

if (str.indexOf(mark) >= 0) {

let getArr = str.split(mark);

return {

getArr,

length: getArr.length

}

}

return false

}

 

//判断为空值 Array Object Number String

export function isEmpty(obj) {

if (!obj) {

return true;

}

//检验null和undefined

if (!obj && obj !== 0 && obj !== '') {

return true;

}

//检验数组

if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) {

return true;

}

//检验对象

if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) {

return true;

}

return false;

 

 

}

 


// 下载excel文件; 参数name是文件名称,res是后端返回的数据

export function downloadExcel(name, res) {

const fileName = name + '.xls' //表格名字

if ('download' in document.createElement('a')) {

// console.log('aaaaaaaaaaaaaaaaaaaa')

// 非IE下载

const blob = new Blob([res], { type: 'application/ms-excel' }) // 解析后端返回的乱码vnd.ms-excel

const elink = document.createElement('a')

// console.log(elink,'elink值')

elink.download = fileName //定义下载名字

elink.style.display = 'none' // 决定是否隐藏

elink.href = URL.createObjectURL(blob)

document.body.appendChild(elink)

elink.click()

URL.revokeObjectURL(elink.href) // 释放URL 对象

document.body.removeChild(elink)

}

}

 

//下载图片

export function downloadImg(imgsrc, name){

console.log('imgsrc, name')

console.log(imgsrc, name)

let image = new Image();

// 解决跨域 Canvas 污染问题

image.setAttribute("crossOrigin", "anonymous");

image.onload = function() {

let canvas = document.createElement("canvas");

canvas.width = image.width;

canvas.height = image.height;

let context = canvas.getContext("2d");

context.drawImage(image, 0, 0, image.width, image.height);

let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

let a = document.createElement("a"); // 生成一个a元素

let event = new MouseEvent("click"); // 创建一个单击事件

a.download = name || "photo"; // 设置图片名称

a.href = url; // 将生成的URL设置为a.href属性

a.dispatchEvent(event); // 触发a的单击事件

};

image.src = imgsrc;

 

}

 

 

//下载文件

export function downloadFile(link, name) {

console.log(link, name)

const x = new XMLHttpRequest();

x.open('GET', link, true);

x.responseType = 'blob';

x.onload = function () {

const url = window.URL.createObjectURL(x.response);

const a = document.createElement('a');

a.href = url;

a.download = name || '';

a.click();

};

x.send();

}

 

//检测数组为空

export function isArrNotEmpty(arr) {

if(arr&&arr.length>0){

return true

}

return false

}

 

// children 属性为空 设置为undefined

export function resetChildren(data) {

const that = this

data.forEach((element) => {

if (element.children && element.children.length > 0) {

resetChildren(element.children)

} else {

element.children = undefined

}

})

return data

}

 

//获取匹配的对象

export function getMatchObj(matchval,matchAtrr,matchArr=[]) {

return matchArr.filter((item)=>{

return matchval==item[matchAtrr]

})

}


/判断数组里是否有相同的值

export function isEqualVal(val,arr=[]) {

let result=arr.filter((item)=>{

return val==item

})

if(result.length>0){

return true

}

return false

}

// 字符串数组互转数字数组 时间比较紧 不自动判断类型 先写死

export function arrTypeTransform(arr,type) {

if(type='Number'){

return arr.map(Number)

}else if(type='String'){

return arr.map(String)

}

}

 

// 去掉字符串空格

export function strTrim(str) {

return str.trim()

}

 

// 判断是否是 空字符 和 null 和 undefined 和 NaN

export function isCheckVal(val) {

if(val===0||val===''||val===null||val===undefined||val===NaN){

return false

}

return true

}

 

export const debounce= (func, wait) => {

var timeout;

 

return function () {

var context = this;

var args = arguments;

 

clearTimeout(timeout)

timeout = setTimeout(function(){

func.apply(context, args)

}, wait);

}

};

 

// 节流

export const throttle = (fn, wait) => {

let canRun = true; // 通过闭包保存一个标记

return function () {

if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return

canRun = false; // 立即设置为false

setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中

fn.apply(this, arguments);

// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉

canRun = true;

}, wait);

};

}

 

// 节流时间范围

export const throttleTime=1000;

 

//获取搜索条件时间

export function getSearchTime(dateArr) {

let dateStr1=new Date(dateArr[0]);

let dateStr2=new Date(dateArr[1]);

// let startDate=Date.parse(dateStr1.getFullYear()+'-'+(dateStr1.getMonth()+1)+'-'+dateStr1.getDate()+' 00:00:00')

// let endDate=Date.parse(dateStr2.getFullYear()+'-'+(dateStr2.getMonth()+1)+'-'+dateStr2.getDate()+' 00:00:00')

let startDate= dateStr1.getFullYear()+'-'+(dateStr1.getMonth()+1)+'-'+dateStr1.getDate()+' 00:00:00'

let endDate=dateStr2.getFullYear()+'-'+(dateStr2.getMonth()+1)+'-'+dateStr2.getDate()+' 23:59:59'

return {

startDate,

endDate

}

}

 

posted @ 2021-07-20 13:36  haveProgress  阅读(276)  评论(0编辑  收藏  举报