本篇文字将分享在工作中十个常用的前端js函数,复制粘贴就能直接用,感觉收藏一波,今天是第一篇
uilts.js
01 自动上传复制图片资源或者远程图片url地址
/** img url 转文件流程 */
const imageToBlob=(image, width, height)=> {
return new Promise((resolve)=>{
let canvas = document.createElement('canvas')
canvas.width = width !== undefined ? width : image.width
canvas.height = height !== undefined ? height : image.height
let ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
canvas.toBlob((blob)=>{
resolve(blob);
})
})
}
/** 生成一个img对象 */
const newImage=(bgcImage)=>{
let image = new Image()
//跨域使用nginx 配置一个头靠谱
// image.crossOrigin = 'anonymous';
image.src = bgcImage
return new Promise((resolve)=>{
image.onload =async() => {
let blob =await imageToBlob(image);
resolve(blob);
}
})
}
/** 是否是一个远程资源 */
const isUrl=(str)=>{
return /((http|ftp|https|file):[^'"\s]+)/gi.test(str)
}
/**
* 绑定事件
* @param {*} successBack 成功回调
* @param {*} element 绑定元素
*/
export const bindUploadFile=(element,successBack)=>{
document.querySelector(element)
.addEventListener('paste', (evt)=> {
let uploadFiles=[];
const data = evt.clipboardData.items;
for (let i = 0; i < data.length; i += 1) {
//如果是一个字符串的url
if ((data[i].kind == 'string') &&
(data[i].type.match('^text/plain'))) {
data[i].getAsString(async(url)=>{
if (isUrl(url)){
const blob=await newImage(url);
uploadFiles.push(blob);
if (i==data.length){
successBack();
}
}
});
//如果是一个文件类型
} else if ((data[i].kind == 'file') &&
(data[i].type.match('^image/'))) {
const blob = data[i].getAsFile();
uploadFiles.push(blob);
if (i==data.length){
successBack();
}
}
}
})
}
开始使用方式:
app.vue
<template>
<section id="uploadImgCom">
<img
v-for="(url,index) in images"
:key="index"
:src="url"/>
</section>
</template>
import {bindUploadFile} from "./uitls"
export default {
data() {
return {
images:[]
}
},
mounted() {
//成功回调
const uploadFileFun=(files)=>{
//最终你可以上传到服务器我这就转成base64地址了
let images=files.map((blob)=>{
return URL.createObjectURL(blob)
});
this.images=images;
};
bindUploadFile("#uploadImgCom",(files)=>{
uploadFileFun(files);
})
},
methods: {
}
};
</script>
<style lang="scss">
#uploadImgCom{
text-align:center;
padding: 52px;
font-size: 25px;
height: 520px;
width: 520px;
background: #f5f5f5;
color: #f5f5f5;
margin: 52px;
border-radius: 6px;
cursor: pointer;
background-color: #000000;
img{
width: 100%;
height: 100%;
}
}
</style>
02数组分割
/**
* 绑定事件
* @param {*} list 被切割的数组
* @param {*} size 切割长度
*/
export const splitArray = (list, size) => {
let length = list.length;
if (length < 1 || size < 1) {
return [];
}
let index = 0;
let lindex = 0;
let result = new Array(Math.ceil(length / size));
while (index < length) {
result[lindex] = list.slice(index, (index += size));
lindex++;
}
return result;
};
开始使用方式:
app.vue
<template>
<section id="uploadImgCom">
<figure v-for="(love,index) in users" :key="index">
<p v-for="(user,cindex) in love" :key="cindex">
{{user.userName}}-{{user.age}}-{{user.sex}}-{{user.attribute}}
</p>
</br>
</figure>
</section>
</template>
import {splitArray} from "./uitls"
//明政局数据
const users=[{
userName:"虎克小哥哥",
age:27,
sex:"男",
attribute:"沙雕"
},
{
userName:"江疏影",
age:32,
sex:"女",
attribute:"虎克小哥哥女朋友"
},
{
userName:"虎克小哥哥",
age:27,
sex:"男",
attribute:"沙雕"
},
{
userName:"江疏影",
age:32,
sex:"女",
attribute:"虎克小哥哥女朋友"
}
]
export default {
data() {
return {
users:[]
}
},
mounted() {
this.users=splitArray(users,2)
},
};
</script>
03格式化人民币
/**
* 格式化人民币
* @param {*} str 人民币数据值
*/
export const formatNum = (str,spStr=',') => {
return `$${str.replace(/\B(?=(\d{3})+(?!\d))/g,spStr)}`;
}
开始使用方式:
app.vue
<section id="uploadImgCom">
虎克小哥哥私有存款:{{money}}
</section>
import {formatNum} from "./uitls"
export default {
data() {
return {
money:'-'
}
},
mounted() {
this.money=formatNum("520520520520");
},
};
</script>
04浏览器重绘成功后触发自定义事件
/**
* 浏览器重绘成功后触发自定义事件
* @param {*} type 事件类型
* @param {*} name 自定义事件名称
* @param {*} obj 触发事件对象
*/
export const bindEvetThrottle=(type, name, obj)=>{
obj = obj || window;
let running = false;
let func = ()=> {
if (running) {
return;
}
running = true;
requestAnimationFrame(()=> {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
}
开始使用方式:
app.vue
<section id="uploadImgCom">
我是一个页面
</section>
import {bindEvetThrottle} from "./uitls"
export default {
mounted() {
//自定义事件名称是不是瞬间高端了
bindEvetThrottle("scroll", "loveScroll");
window.addEventListener("loveScroll", ()=> {
console.log("虎克小哥哥");
});
},
};
</script>
05格式化日期
/**
* 格式化日期
* @param {*} val 时间值
* @param {*} format 格式
*/
const fNum = n => (parseInt(n, 10) < 10 ? `0${n}` : `${n}`);
export let formatDate = (val, format = "YYYY-MM-DD hh:mm:ss") => {
if (typeof val === "string") {
val = val.replace(/-/g, "/");
}
let date = new Date(val);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let week = date.getDay();
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
let time = date.getTime();
if (format === "time" || format === "Time") {
return time;
}
let chinese = ["一", "二", "三", "四", "五", "六", "日"];
format = format.replace(/YYYY/, year);
format = format.replace(/YY/, (String(year)).slice(2));
format = format.replace(/MM/, fNum(month));
format = format.replace(/M/, month);
format = format.replace(/[wW]+/, `星期${chinese[week]}`);
format = format.replace(/DD/, fNum(day));
format = format.replace(/D/, day);
format = format.replace(/hh/, fNum(hour));
format = format.replace(/h/, hour);
format = format.replace(/mm/, fNum(minute));
format = format.replace(/m/, minute);
format = format.replace(/ss/, fNum(second));
format = format.replace(/s/, second);
return format;
};
开始使用方式:
app.vue
<section id="uploadImgCom">
现在是:{{createtime},关机下班,感觉滚
</section>
import {formatDate} from "./uitls"
export default {
data() {
return {
createtime:'-'
}
},
mounted() {
this.createtime=formatDate(new Date());
},
};
</script>
🎨下一篇:十个函数(02)
🎨 原创不易,支持请点赞、转发和关注我,后续持续更新原创文章
🎨个人微信欢迎来撩,妹子更好
