Web前端最新前端常用工具库方法整理,web开发工程师

文末

从转行到现在,差不多两年的时间,虽不能和大佬相比,但也是学了很多东西。我个人在学习的过程中,习惯简单做做笔记,方便自己复习的时候能够快速理解,现在将自己的笔记分享出来,和大家共同学习。

个人将这段时间所学的知识,分为三个阶段:

第一阶段:HTML&CSS&JavaScript基础

第二阶段:移动端开发技术

第三阶段:前端常用框架

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

  • 推荐学习方式:针对某个知识点,可以先简单过一下我的笔记,如果理解,那是最好,可以帮助快速解决问题;

  • 大厂的面试难在,针对一个基础知识点,比如JS的事件循环机制,不会上来就问概念,而是换个角度,从题目入手,看你是否真正掌握。所以对于概念的理解真的很重要。

    ctx.drawImage(img, 0, 0, img.width, img.height);
    let dataUrl = canvas.toDataURL("image/jpeg");
    canvas = null;
    resolve(dataUrl);
    

    };
    });
    },


###### 9.常用code码统一报错提示



const codeMessage = {
200: ‘服务器成功返回请求的数据。’,
201: ‘新建或修改数据成功。’,
202: ‘一个请求已经进入后台排队(异步任务)。’,
204: ‘删除数据成功。’,
400: ‘发出的请求有错误,服务器没有进行新建或修改数据的操作。’,
401: ‘用户没有权限(令牌、用户名、密码错误)。’,
403: ‘用户得到授权,但是访问是被禁止的。’,
404: ‘发出的请求针对的是不存在的记录,服务器没有进行操作。’,
406: ‘请求的格式不可得。’,
410: ‘请求的资源被永久删除,且不会再得到的。’,
422: ‘当创建一个对象时,发生一个验证错误。’,
500: ‘服务器发生错误,请检查服务器。’,
502: ‘网关错误。’,
503: ‘服务不可用,服务器暂时过载或维护。’,
504: ‘网关超时。’,
};


###### 10.原生ajax下载导出



/**
* @param {String} url 下载URL地址
* @param {String|Number} downloadName 下载文件名称
* @Parma {type} 下载请求方法get||post
* @description 导出Excel文件
* */
import Vue from ‘vue’;
import moment from ‘moment’;
import Cookies from “js-cookie”;
const that = new Vue();

export function fileDownload(url, downloadName = moment(new Date(), ‘YYYY-MM-DD’) + “任务监控数据表”, option) {
const { type, status, message, messageErr, params } = option;

let fileName = downloadName + ‘.xlsx’;

let request = new XMLHttpRequest();

status ? that.$message({
type: ‘warning’,
showClose: true,
message: message || ‘已点击正在下载,请稍后…’,
}) : null;

request.open(type || ‘GET’, url, true);

request.setRequestHeader(“Authorization”, Cookies.get(“user-token”));

request.setRequestHeader(
“Content-Type”,
params ? ‘application/json’ : “application/x-www-form-urlencoded; charset=UTF-8”
);

request.responseType = “blob”;

request.onload = function () {
if (this.status === 200) {
let blob = this.response;
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, fileName);
} else {
let downloadLink = document.createElement(“a”);
let contentTypeHeader = request.getResponseHeader(“Content-Type”);
downloadLink.href = window.URL.createObjectURL(
new Blob([blob], { type: contentTypeHeader })
);
downloadLink.download = fileName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
window.URL.revokeObjectURL(downloadLink.href)
}
} else {
that.$message({
type: ‘error’,
showClose: true,
message: messageErr ||‘文件下载失败…’,
});
}
};
request.send(params ? JSON.stringify(params) : void null);
}


###### 10.file文件转码



const toDataUrl = (blob) => {
return new Promise(resolve => {
let file = new FileReader();
file.onload = event => {
resolve(event.target.result);
};
file.readAsDataURL(blob);
});
},


###### 11. url参数加密



export const Base64 = {
//加密
encode(params) {
return btoa(encodeURIComponent(params).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, option) {
return String.fromCharCode(‘0x’ + option);
}));
},
//解密
decode(params) {
return decodeURIComponent(atob(params.replace(/\s/g, ‘+’)).split(‘’).map(option => ‘%’ + (‘00’ + option.charCodeAt(0).toString(16)).slice(-2)).join(‘’));
}
}



> 
> \s : 表示 space ,空格  
>  +: 一个或多个  
>  ^: 开始,^\s,以空格开始 结束,\s$,以空格结束  
>  |:或者  
>  /g:global, 全局
> 
> 
> 


###### 12. 背景水印



‘use strict’

const watermark = {};

/**
* @param {String} str // 要设置的水印的内容
* @param {String} container // 需要设置水印的容器
*/
const id = ‘1.23452384164.123412415’;

const setWatermark = (str, container) => {
if (!container) return false;

if (document.getElementById(id) !== null) { // 查看页面上有没有,如果有则删除
const childelement = document.getElementById(id)
childelement.parentNode.removeChild(childelement)
}

const containerWidth = container.offsetWidth // 获取父容器宽
const containerHeight = Math.max(container.scrollHeight, document.body.clientHeight); // 获取父容器高
container.style.position = ‘relative’ // 设置布局为相对布局

const can = document.createElement(‘canvas’) // 创建canvas元素(先制作一块背景图)
can.width = 300 // 设置每一块的宽度
can.height = 200 // 高度
const cans = can.getContext(‘2d’) // 获取canvas画布
cans.rotate(20 * Math.PI / 180) // 逆时针旋转π/9
cans.font = ‘14px Microsoft JhengHei’; // 设置字体
cans.fillStyle = ‘rgba(17, 17, 17, 0.2)’ // 设置字体的颜色
cans.textAlign = ‘left’ // 文本对齐方式
cans.textBaseline = ‘Middle’ // 文本基线
cans.fillText(str, can.width / 3, can.height / 2); // 绘制文字

const div = document.createElement(‘div’) // 创建一个div元素
div.id = id // 设置id
div.style.pointerEvents = ‘none’ // 取消所有事件
div.style.top = ‘0px’
div.style.left = ‘0px’
div.style.position = ‘absolute’
div.style.zIndex = ‘10000’
div.style.width = containerWidth + ‘px’
div.style.height = containerHeight + ‘px’
div.style.background = ‘url(’ + dataURLtoBlob(can.toDataURL(‘image/png’)) + ‘)’
container.appendChild(div) // 追加到页面
return id
}

function dataURLtoBlob(dataurl) {
let arr = dataurl.split(‘,’);
let mime = arr[0].match(/😦.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n–) {
u8arr[n] = bstr.charCodeAt(n);
}
return URL.createObjectURL(new Blob([u8arr], { type: mime }));
}

let _interval = null;

// 该方法只允许调用一次
watermark.set = (str, container) => {
let id = setWatermark(str, container)
_interval = setInterval(() => {
if (document.getElementById(id) === null) {
id = setWatermark(str, container)
}
}, 500)
window.onresize = () => { // 监听页面大小的变化
setWatermark(str, container)
}
}

export default watermark;


###### 12. 随机生成颜色



getArrRandomly() {
const tagsColor = [“info”, “warning”, “danger”, “”];
var colorIndex = Math.floor(Math.random() * tagsColor.length);
var color = tagsColor[colorIndex];
tagsColor.splice(colorIndex, 1);
return color;
},


###### 13. 倒计时



startTime(bolean, endTimer) {
let minute = 0
let second = 0
const that = this
if (endTimer) {
;[minute, second] = this.callinTime.split(‘:’)
minute = Number(minute)
second = Number(second)
}
if (bolean === true) {
that.timer = setInterval(() => {
if (second >= 0) {
second = second + 1
}
if (second >= 60) {
second = 0
minute = minute + 1
}
if (endTimer && that.callinTime === endTimer) {
this.suspendStatus = false
this.callinTime = ‘00:00’
return clearInterval(that.timer)
}
that.callinTime =
(minute < 10 ? ‘0’ + minute : minute) +
‘:’ +
(second < 10 ? ‘0’ + second : second)
}, 1000)
} else {
clearInterval(that.timer)
}
}


###### 14. 金额转换



function toThousands(num) {
if (num && num.toString().length > 4) {
const result = num.toString().replace(/(\d)(?=(?:\d{4})+$)/g, ‘$1.’)
return Number(result).toFixed(1) + ‘w’
}
return num
}


###### 15. 页面滚动监听事件,实现滚动加载



// 页面滚动监听事件
export function scrollToBottom(callBack: any) {
window.onscroll = () => {
let scrollTop = 0
let bodyScrollTop = 0
let documentScrollTop = 0
if (document.body) {
bodyScrollTop = document.body.scrollTop
}
if (document.documentElement) {
documentScrollTop = document.documentElement.scrollTop
}
scrollTop =
bodyScrollTop - documentScrollTop > 0 ? bodyScrollTop : documentScrollTop
let scrollHeight = 0
let bodyScrollHeight = 0
let documentScrollHeight = 0
if (document.body) {
bodyScrollHeight = document.body.scrollHeight
}
if (document.documentElement) {
documentScrollHeight = document.documentElement.scrollHeight
}
// 获取文档元素的内容垂直滚动的像素数
scrollHeight =
bodyScrollHeight - documentScrollHeight > 0
? bodyScrollHeight
: documentScrollHeight
let windowHeight = 0
// 判断当前文档的渲染模式是混杂模式还是"标准模式"
if (document.compatMode === ‘CSS1Compat’) {
// “标准模式”或者“准标准模式(almost standards mode)”
windowHeight = document.documentElement.clientHeight
} else {
// 混杂模式,值为"BackCompat"
windowHeight = document.body.clientHeight
}
// 若文档内容垂直滚动像素 + 当前窗口高度的像素 === document.body.scrollHeight或document.documentElement.scrollHeight返回Promise对象,执行后续操作
if (scrollHeight - (scrollTop + windowHeight) < 1000) {
callBack()
}
}
}

// 使用
scrollToBottom(() => {
if (!this.loadMore) return false
this.getDataList()
})


###### 16. 两数组重组json



// 数据匹配重组
function filterDataList(data, targetArr, option) {
const { lable } = option
const array = [];
for (let i = 0; i < data.length; i++) {
const item = data[i]
array.push(item);
for (let j = 0; j < targetArr.length; j++) {
if (item[lable] === item[lable]) {
array[i] = Object.assign({}, item, targetArr[j]); //合并对象
targetArr.splice(j, 1); //删除本次合并的对象,增加性能
break;
}
}
}
return array;
}


###### 17. 图片压缩



const MAX_SIZE = 10485760 //图片最大字节数

function compressImg(file, quality) {
let reader = new FileReader()
let image = new Image()
let canvas = document.createElement(‘canvas’);
let context = canvas.getContext(‘2d’);
return new Promise(resolve => {
reader.readAsDataURL(file) // 文件base64化,以便获知图片原始尺寸
reader.onload = e => image.src = e.target.result;
image.onload = _ => {
let originWidth = image.width;
let originHeight = image.height;
let targetWidth = originWidth, targetHeight = originHeight;
canvas.width = targetWidth; // canvas对图片进行缩放
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight); // 清除画布
context.drawImage(image, 0, 0, targetWidth, targetHeight); // 图片压缩
canvas.toBlob(blob => { //压缩后的图片base64 url /*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是’image/jpeg’; * qualityArgument表示导出的图片质量,只要导出为jpg和webp格式的时候此参数才有效果,默认值是0.92*/
if (blob.size > MAX_SIZE) {
alert(‘最大只允许上传10MB哦~’)
resolve()
} else {
resolve(blob)
}
}, ‘image/jpeg’, quality)
}
})
}

//计算压缩质量
function computedQuality(size, max, count = 1) {
if (size >= max) {
if (count > 1) {
return 0.1 * count - .1
} else {
return 0.1 * count
}
} else {
if (max - EVA <= 0) {
return .9
} else {
return computedQuality(size, max - EVA, ++count)
}
}
}


###### 18. 计算两个日期时间相差的年数、月数、天数、日期时间



/**
* 计算两个日期时间相差的年数、月数、天数、日期时间
* console.log(formatExpirationTime(‘2019-6-30’, ‘2020-10-01’))
*/

export const formatExpirationTime = (startTime, endTime) => {
function getDays(mouth, year) {
let days = 30
if (mouth === 2) {
days = year % 4 === 0 ? 29 : 28
} else if (
mouth === 1 ||
mouth === 3 ||
mouth === 5 ||
mouth === 7 ||
mouth === 8 ||
mouth === 10 ||
mouth === 12
) {
days = 31
}
return days
}

const start: any = new Date(startTime)
const end: any = new Date(endTime)
const diffValue = end - start

const startYear = start.getFullYear()
const endYear = end.getFullYear()
const startMouth = start.getMonth() + 1
const endMouth = end.getMonth() + 1
const startDay = start.getDate()
const endDay = end.getDate()
const startHours = start.getHours()
const endHours = end.getHours()
const startMinutes = start.getMinutes()
const endMinutes = end.getMinutes()
const startSeconds = start.getSeconds()
const endSeconds = end.getSeconds()

if (diffValue >= 8.64e7 * 30) {
const diffYear = endYear - startYear
const startDays = getDays(startMouth, startYear)
const endDays = getDays(endMouth, endYear)

const diffStartMouth =
  (startDays - (startDay + (startHours \* 60 + startMinutes + startSeconds / 60) / 60 / 24 - 1)) /
  startDays

const diffEndMouth = (endDay + (endHours \* 60 + endMinutes + endSeconds / 60) / 60 / 24 - 1) / endDays

const diffMouth = diffStartMouth + diffEndMouth + (12 - startMouth - 1) + endMouth + (diffYear - 1) \* 12

if (diffValue >= 8.64e7 \* 365) {
  const diffYear = Math.floor((diffMouth / 12) \* 100) / 100
  const year = parseInt((((diffMouth / 12) \* 100) / 100).toString())
  const mouth = (diffYear % year) \* 12
  return year + '年' + (mouth ? mouth + '月' : '')
} else {
  return Math.floor(diffMouth) + '月'
}

} else if (diffValue >= 8.64e7) {
const d = parseInt((diffValue / 1000 / 60 / 60 / 24).toString())
return d + ‘天’
} else {
return endTime
}
}


###### 19. bytesToSize



export const bytesToSize = (size) => {
if (!size) return ‘0.00’;
const pow1024 = (num) => Math.pow(1024, num)
if (size < pow1024(1)) return size + ’ B’;
if (size < pow1024(2)) return (size / pow1024(1)).toFixed(2) + ’ KB’;
if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2) + ’ MB’;
if (size < pow1024(4)) return (size / pow1024(3)).toFixed(2) + ’ GB’;
return (size / pow1024(4)).toFixed(2) + ’ TB’
}


##### 20. 用js实现可终止的轮询请求



> 
> 1. 按照需要选择是否立即发起请求再进入轮询
> 2. 上一次的请求响应后到了指定的时间间隔后再继续执行下一次请求
> 3. 当轮询的请求发生报错的时候应该停止轮询
> 4. 被停止的轮询可以根据需要再次发起轮询
> 
> 
> 



/**
* @descripting 轮询功能
* @param {Function} callback 回调事件
* @param {Number} interval 轮询间隔时间
*/
export const pollingHttp = (callback, interval = 2000) => {
let timer, isStop = false

const stop = () => {
isStop = true
clearTimeout(timer)
}

const start = async () => {
isStop = false
await loopEvent()
}

const loopEvent = async () => {
try {
await callback(stop)
} catch (err) {
throw new Error(‘轮询出错:’, err)
}
if (isStop) return
return (timer = setTimeout(loopEvent, interval))
}

return { start, stop }
}



> 
> 模拟请求使用
> 
> 
> 



import { pollingHttp } from ‘@/utils/utilTool’

const arr = ref<any[]>([])

const intervalManager = pollingHttp(async (stop) => {
const res: any = await api.hostmanage({ curPage: 1, pageSize: 10 }, ‘get’)
if (res?.code === 0) {
const { data, durationSecond } = res.data
arr.value.push(…data)
console.log(arr, ‘res’)
if (durationSecond === 100) {
stop()
}
}
}
}, 3000)


##### 21. 一维数组将相同id放置到一个对象内,组成新数组



formatterDataSource(data) {
const groupedData = data.reduce((acc, curr) => {
const id = curr.graphType === 8 ? curr.serverMeta?.id : false ;
if (!id) {
return acc;
}
if (!acc[id]) {
acc[id] = [];
}
acc[id].push(curr);
return acc;
}, {});

const newData = Object.values(groupedData).map((group) => {
  if (group.length === 1) {
    return group[0];
  }
  const obj = { graphType: 11.11, ...group[0] };
  group.forEach((item, index) => {obj[index] = item });
  return obj;

文末

从转行到现在,差不多两年的时间,虽不能和大佬相比,但也是学了很多东西。我个人在学习的过程中,习惯简单做做笔记,方便自己复习的时候能够快速理解,现在将自己的笔记分享出来,和大家共同学习。

个人将这段时间所学的知识,分为三个阶段:

第一阶段:HTML&CSS&JavaScript基础

第二阶段:移动端开发技术

第三阶段:前端常用框架

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

  • 推荐学习方式:针对某个知识点,可以先简单过一下我的笔记,如果理解,那是最好,可以帮助快速解决问题;

  • 大厂的面试难在,针对一个基础知识点,比如JS的事件循环机制,不会上来就问概念,而是换个角度,从题目入手,看你是否真正掌握。所以对于概念的理解真的很重要。

  • 28
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值