持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情
不管在平时写代码还是项目中完成需求时,总避免不了使用到一些常见但又需要重复编写的功能函数,为此,本文记录了一些工作中经常用到的功能,并以封装函数的形式呈现,可以方便后续重复使用。
- 微信小程序中网络图片转为base64格式图片
// 网络图片转为base64
const netimage_to_base64 = (img) => {
return new Promise(((resolve, reject) => {
wx.downloadFile({
url: img,
success(res) {
wx.getFileSystemManager().readFile({
filePath: res.tempFilePath, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
resolve(res.data);
}
});
}
});
}));
}
- 本地图片转为base64图片
// 本地图片转为base64
const localimage_to_base64 = (tempFilePath) => {
// 创建文件管理类
const fileManager = wx.getFileSystemManager();
// 读取本地文件,直接得到base64
const base64 = fileManager.readFileSync(tempFilePath, 'base64');
return base64;
}
- 数字千分符转换
将一个数字转换为每三位以逗号(,)分隔的形式,比如23453.87,转换为千分符形式后为23,453.87
const formatThousands = (value: number) => {
if (typeof value !== 'number') return;
let formatValue: string = String(value);
let reg = /^(-?\d+)(\d{3})(\.?\d*)/;
while (reg.test(formatValue)) {
formatValue = formatValue.replace(reg, "$1,$2$3");
}
return formatValue;
};
- 获取url地址中的参数
将url中的查询参数提取出来,转换为键值对形式的数据对象并返回
const getURLParams = (url: string = window.location.href) =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce((params: any, pair) => {
const [key, value] = pair.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(value);
return params;
}, {});
- 将参数对象序列化为查询字符串
即将参数对象params的键值对都转换为使用"&"符号连接,并且键(key)与值(value)使用"="连接的字符串形式
// 将key-values转换为"="连接的字符串形式,encode表示是否编码
export const serializeParameter = (
k: any,
v: any = "",
encode: boolean = true
) =>
encode ? `${encodeURIComponent(k)}=${encodeURIComponent(v)}` : `${k}=${v}`;
// 处理参数对象params,调用serializeParameter方法
const serializeParameters = (
params: any,
encode: boolean = true,
) =>
Object.keys(params)
.reduce((query: any, key) => {
const val = params[key];
query.push(serializeParameter(key, val, encode));
return query;
}, [])
.join("&");
- 生成随机字符串
使用Math.random()方法结合toString()方法,由于这样产生的字符串类似"",因此再使用subString()方法从第二位开始截取
const randomString = () => {
return Math.random().toString(36).substring(2);
};
- 检验字符串中是否含有中文字符
const judgeHasChinese = (value: string) => {
const isHasChinese: boolean = /[\u4e00-\u9fa5]/.test(value);
if (isHasChinese) {
return Promise.resolve();
} else {
return Promise.reject(new Error('不能含有中文字符'));
}
};
- 防抖函数
在函数内部设定定时器,返回一个新的函数,在新函数内部每次先调用清除定时器的方法,然后调用setTimeout方法,传入其他参数;
如下方法中,参数fn为一个函数,表示需要去抖的函数,第二个参数为一个对象,其中包括delay需要延迟的时间,单位为毫秒ms,context为上下文,默认为null。
const debounce = (fn: Function, {delay = 0,context = null} = {}) => {
let timeoutId: any;
return function(...args){
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(context, args), delay)
}
}
使用方法如下:
const handleSearch = (searchVal) => {
console.log('value is', searchVal);
}
debounce(handleSearch, {delay: 500 })