实际前端开发中,常用工具方法的封装JS
主要包括以下
- 设置获取Cookie
- 各种文件下载到本地
- 3天前~一周前
- 字符串加密
- 深拷贝
- 复制数据
- 格式化文件大小
- 自定义处理日期
- … 本文章,持续更新中… 会不断的上传实际开发中用到的工具方法封装,
设置获取Cookie
/**
* 设置cookie
* @param name 字段名
* @param value 值
* @param seconds 失效时长
* setCookie(name, "", -1); 删除cookie
*/
export function setCookie(name, value, seconds) {
seconds = seconds || 0; // seconds有值就直接赋值,没有为0
let expires = '';
if (seconds !== 0) {
// 设置cookie生存时间
const date = new Date();
date.setTime(date.getTime() + seconds * 1000);
expires = '; expires=' + date['toGMTString']();
}
document.cookie = name + '=' + escape(value) + expires + '; path=/';
}
/**
* 获取cookie
* @param name 字段名
*/
export function getCookie(name) {
if (document.cookie.length > 0) {
let start = document.cookie.indexOf(name + '=');
if (start !== -1) {
start = start + name.length + 1;
let end = document.cookie.indexOf(';', start);
if (end === -1) end = document.cookie.length;
return unescape(document.cookie.substring(start, end)).replace(/'/g, '');
}
}
return null;
}
各种文件下载到本地
接口返回的是字节流
url是接口地址,且该接口返回的是blob
/**
* random string
* @param {params} 参数
* @param {url} 下载文件的接口地址
* @param {fileType} 下载的文件类型
*/
// 'application/zip'
export function downFileToBD(params, url, fileType) {
axios.get(
url,//请求的url
{params,
responseType:'blob'//服务器返回的数据类型
}).then((res)=>{
// 处理返回的文件流
const content = res.data;
const blob = new Blob([content], { type: fileType });
if ("download" in document.createElement("a")) {
// 非IE下载
const elink = document.createElement("a");
elink.download = params.modelName; // 如果有后缀名, 则会作为下载文件的后缀名
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} else {
// IE10+下载
navigator.msSaveBlob(blob, params.modelName);
}
})
}
或者
// 接口需要设置:responseType: ‘blob’
export const downloadWordFile = async (
wordBlob: any,
responseType: string,
wordFileName: any = new Date().valueOf()
) => {
const blob = new Blob([wordBlob], { type: responseType }) // 把得到的结果用流对象转一下
const a = document.createElement('a') // 创建一个<a></a>标签
a.href = URL.createObjectURL(blob) // 将流文件写入a标签的href属性值
a.download = wordFileName // 设置文件名
a.style.display = 'none' // 障眼法藏起来a标签
document.body.appendChild(a) // 将a标签追加到文档对象中
a.click() // 模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
a.remove() // 一次性的,用完就删除a标签
}
接口返回的是文件url地址
fetch(接口返回的fileUrl).then((res) =>
res.blob().then((blob) => {
const a = document.createElement('a');
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}),
);
3天前~一周前
export const handlePublishTimeDesc = (time) => {
const curTime = new Date().getTime();
const postTime = new Date(time).getTime();
const timeDiff = curTime - postTime;
// 单位换算
const min = 60 * 1000;
const hour = min * 60;
const day = hour * 24;
const week = day * 7;
const month = week * 4;
const year = month * 12;
// 计算发布时间距离当前时间的周、天、时、分
// const exceedyear = Math.floor(timeDiff / year);
// const exceedmonth = Math.floor(timeDiff / month);
// const exceedWeek = Math.floor(timeDiff / week);
const exceedDay = Math.floor(timeDiff / day);
const exceedHour = Math.floor(timeDiff / hour);
const exceedMin = Math.floor(timeDiff / min);
// 最后判断时间差到底是属于哪个区间,然后return
if (exceedDay > 7) {
return transformTime(time, true);
}
if (exceedDay <= 7 && exceedDay > 0) {
return exceedDay + '天前';
} else {
if (exceedHour < 24 && exceedHour > 0) {
return exceedHour + '小时前';
} else {
return exceedMin + '分钟前';
}
}
};
各种文件预览
1、pdf的Blob之 将Blob转换为临时地址,在新页签打开
// res: Blob对象 type: application/pdf
export const previewPdfFile = (res: any, type: string) => {
const url = URL.createObjectURL(
new Blob([res], {
type,
})
)
window.open(url, '_blank')
URL.revokeObjectURL(url) // 释放内存
}
2、word的Blob之 使用第三方插件docx-preview:通过Blob流预览word文件
$ pnpm i docx-preview
<template>
<div class="word-preview" ref="wordPreviewRef"></div>
</template>
<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { renderAsync } from 'docx-preview'
const props = defineProps<{
wordBlob: any
}>()
const wordPreviewRef = ref({})
nextTick(() => {
renderAsync(
props.wordBlob,
wordPreviewRef.value as HTMLElement // HTMLElement 渲染文档内容的元素,
)
})
</script>
<style lang="scss" scoped>
.word-preview {
width: 100%;
height: 100%;
}
</style>
3、excel文件预览
安装依赖 yarn add xlsx
<div class="xlsxClass"></div>
const reader = new FileReader();
//通过readAsArrayBuffer将blob转换为ArrayBuffer对
reader.readAsArrayBuffer(res.data) // 这里的res.data是blob文件流
reader.onload = (event) => {
// 读取ArrayBuffer数据变成Uint8Array
var data = new Uint8Array(event.target.result);
// 这里的data里面的类型和后面的type类型要对应
var workbook = XLSX.read(data, { type: "array" });
var sheetNames = workbook.SheetNames; // 工作表名称
var worksheet = workbook.Sheets[sheetNames[0]];
// var excelData = XLSX.utils.sheet_to_json(worksheet); //JSON
let html = XLSX.utils.sheet_to_html(worksheet);
document.getElementsByClassName('xlsxClass')[0].innerHTML = html
};
字符串加密
/**
* 加密
* @param {string} value 要加密的字符串
* @param {string} publicKey 公钥
*/
export const encryption = (value, publicKey) => {
// 随机生成16位字符串的key
const key = createNonceStr();
// 转成16进制的key
const key_16 = stringToHex(key);
// sm4加密:用key_16将密码加密
const newPassword = encryptSm4(value, key_16);
// node-rsa加密:用公钥将key加密
const newKeys = encryptRsa(key, publicKey);
// 拼接
return `{${newKeys}}${newPassword}`;
};
深拷贝
// 深拷贝
export const deepCopy = (obj) => {
const newObj = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (key && obj.hasOwnProperty(key)) {
let newSubObj = obj[key];
if (obj[key] && typeof obj[key] === 'object') {
newSubObj = deepCopy(obj[key]);
}
// todo 暂不复制方法
if (obj[key] && typeof obj[key] === 'function') {
continue;
}
newObj[key] = newSubObj;
}
}
return newObj;
};
深拷贝方法二
// 深拷贝
export const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));
复制数据
// 复制数据
export const copyData = (that, data, message) => {
that.$copyText(data).then(
() => {
that.$message({
showClose: true,
message: message || '已复制',
type: 'success',
});
},
() => {
that.$message({
showClose: true,
message: '复制失败',
type: 'error',
});
}
);
};
格式化文件大小
/**
* @param {*} size 文件大小
* @description 根据文件大小设置对应的文件单位
*/
export const setFileSizeUnit = (size) => {
const fileSize =
size >= 1024
? size / 1024 >= 1024
? size / 1024 / 1024 >= 1024
? (size / 1024 / 1024 / 1024).toFixed(2) + 'GB'
: (size / 1024 / 1024).toFixed(2) + 'MB'
: (size / 1024).toFixed(2) + 'kB'
: size.toFixed(2) + 'B';
return fileSize;
};
大数字转换,将大额数字转换为万、千万、亿等
export function bigNumberTransform(num: number) {
if (num < 1000) {
return num.toString()
}
if (num < 10000) {
return `${(num / 1000).toFixed(1)}千`
}
if (num < 100000000) {
return `${(num / 10000).toFixed(1)}万`
}
return `${(num / 100000000).toFixed(1)}亿`
}
自定义处理日期
/**
* @param {*} time 时间戳
* @param {*} separator 分隔符
* @description 处理时间(将时间戳转换成年月日格式日期)
*/
export const transformDate = (time, separator = '/') => {
const date = new Date(time);
const year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
return `${year}${separator}${month}${separator}${day}`;
};
/**
* @param {*} time 时间戳
* @description 处理时间(将时间戳转换成年月日时分格式)
*/
export const transformTime = (time, short) => {
const date = new Date(time);
const year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let h = date.getHours();
let m = date.getMinutes();
let s = date.getSeconds();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
s = s < 10 ? '0' + s : s;
if (short) {
return `${year}-${month}-${day}`;
}
return `${year}-${month}-${day} ${h}:${m}:${s}`;
};
对UTC 时间格式转换成正常时间显示
UTC 时间格式: 例如 2014-11-11T12:00:00Z
// 对UTC 时间格式转换成正常时间显示
export const UTCDateString = (UTCDateString) => {
if (!UTCDateString) {
return '-';
}
function formatFunc(str) {
return str > 9 ? str : '0' + str;
}
var date2 = new Date(UTCDateString);
var year = date2.getFullYear();
var mon = formatFunc(date2.getMonth() + 1);
var day = formatFunc(date2.getDate());
var hour = date2.getHours();
var noon = hour >= 12 ? 'PM' : 'AM'; // 判断是上午还是下午
hour = hour >= 12 ? hour - 12 : hour; // 12小时制
hour = formatFunc(hour);
var min = formatFunc(date2.getMinutes());
var sec = formatFunc(date2.getSeconds());
// var dateStr = year + '-' + mon + '-' + day + ' ' + hour + ':' + min + ':' + sec;
var dateStr = year + '-' + mon + '-' + day;
return dateStr;
};
生成随机颜色
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}` // 生成随机颜色
复制到剪切版
const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard("Hello World!")
深拷贝对象
const deepCopy = obj => JSON.parse(JSON.stringify(obj))
本文章,持续更新中… 会不断的上传实际开发中用到的工具方法封装,兄弟姐妹们如果有常用的工具方法需要补充,可以留言或者私信我
前端分页
/**
* 前端分页,不再次请求接口,不破坏原数组list
* @param list 请求接口返回的全部数据
* @param pageSize 一页展示的数据个数
* @param currentPage 当前页码
* @returns []
*/
export function getPagination(list, pageSize, currentPage) {
let dataSource = [];
if (list.length < pageSize) {
//判断当前获取的接口数据的长度是否大于设置的展示个数(总页数是否大于1)
const index = (currentPage - 1) * pageSize;
dataSource = list.slice(index, pageSize); //截取当页展示数据
} else if (currentPage === Math.ceil(list.length / pageSize)) {
//当前页码是否为最后一页
const index = (currentPage - 1) * pageSize;
dataSource = list.slice(index);
} else {
/**
* 若总页数大于1,且当前页码不是最后一页时
* 获取下标(index)截取数据(dataSource)
*/
const index = (currentPage - 1) * pageSize;
dataSource = list.slice(index, currentPage * pageSize);
}
return dataSource;
}
本人微信:

本文提供了一系列前端开发中常用的工具方法封装,包括获取Cookie、文件下载、预览、加密、深拷贝、复制数据、格式化文件大小、日期处理、颜色生成、剪切板复制及分页等。
6091

被折叠的 条评论
为什么被折叠?



