function hexToRgb(hex) {
// 移除十六进制颜色代码中的'#'
let sanitizedHex = hex.replace("#", "");
// 解析红、绿、蓝各自的十六进制数
let r = parseInt(sanitizedHex.substring(0, 2), 16);
let g = parseInt(sanitizedHex.substring(2, 4), 16);
let b = parseInt(sanitizedHex.substring(4, 6), 16);
return `rgb(${r}, ${g}, ${b})`;
}
// animationFn
export default function animationFn(option, callback): void {
const { from, to, duration, decimalCount } = Object.assign(
{
duration: 400,
decimalCount: 0
},
option
);
const dis = to - from;
const speed = dis / duration;
const startT = performance.now();
let value = Number(from.toFixed(decimalCount)); //当前的值
callback(value);
function _run(timeStamp) {
const time = timeStamp - startT;
if (time >= duration) {
value = to;
callback(value);
return;
}
const d = time * speed; //删除得到数值的小数部分
value = Number((from + d).toFixed(decimalCount)); //当前的值
callback(value);
requestAnimationFrame(_run);
}
requestAnimationFrame(_run);
}
// toThousands
export const toThousands = (Num, isFixed = true) => {
// 例(123456.78)
const oldNum = Number(Num);
if (oldNum === 0) return 0; // 传入的数值为空直接返回空对象
let newNum = oldNum.toLocaleString('en-US'); // 数字转成千分位 = 123,456.78
const numArr = newNum.split('.'); // 按小数点吧数字拆分 = [123,456, 78]
if (!isFixed) {
// 如果传了第二个参数,如果有小数位直接返回,否则向下执行
if (!numArr[1]) {
// 如果数组没有下标1的元素,就加.00,例:123,456 = 123,456.00
newNum = newNum + '.00';
} else if (numArr[1].length === 1) {
// 如果数组下标1的元素只有一位小数,就加个0,例:123,456.7 = 123,456.70
newNum = newNum + '0';
} else if (numArr[1].length >= 2) {
// // 如果数组下标1的元素小数位大于等于2位,就截取前两位,例:123,456.789 = 123,456.78
newNum = numArr[0] + '.' + numArr[1].substr(0, 2);
}
}
return newNum;
};
// vNumberLazy
const vNumberLazy: Directive = (el, binding) => {
const {
value = 0,
arg,
modifiers: { isThousands }
} = binding;
// 指令默认参数
const defaultAArg = [400, 0];
// 获取传入指令的参数,通过 v-numberLazy:param1:param2的方式传入 ,param1为动画执行时间,param2为保留小数位数
const aArg = Object.assign(defaultAArg, typeof arg === 'string' ? arg.split(':').map((item) => Number(item)) : []);
const numValue = Number(value);
if (typeof numValue !== 'number') {
throw new Error('v-numberLazy只能接受数字类型参数');
} else {
animationFn(
{
from: 0,
to: numValue,
duration: aArg[0],
decimalCount: aArg[1]
},
(val) => {
el.textContent = isThousands ? toThousands(val, true) : val;
}
);
}
};
export default vNumberLazy;
// 使用 v-numberLazy:400:2.isThousands="1000"