better animated number

This commit is contained in:
Timi
2026-10-16 16:41:03 +08:00
parent 89b4a67551
commit 5b4f588cfb
5 changed files with 152 additions and 38 deletions
+5
View File
@@ -0,0 +1,5 @@
import view from "./index.vue";
import WebToolkit from "../../utils/WebToolkit";
export const AnimatedAmount = WebToolkit.withInstall(view);
export default AnimatedAmount;
+61
View File
@@ -0,0 +1,61 @@
<template>
<animated-number
:value="scaledValue"
:prefix="prefix"
:suffix="suffix"
:empty-text="emptyText"
:decimals="decimals"
:duration="duration"
>
<template v-if="$slots.prefix" #prefix>
<slot name="prefix" />
</template>
<template v-if="$slots.suffix" #suffix>
<slot name="suffix" />
</template>
<template v-if="$slots.empty" #empty>
<slot name="empty" />
</template>
</animated-number>
</template>
<script lang="ts" setup>
import AnimatedNumber from "../animated-number";
defineOptions({
name: "AnimatedAmount"
});
const props = withDefaults(defineProps<{
/** 原始数值或数值 getter,为空时隐藏 */
value?: number | null | (() => number | null | undefined);
/** 数值前缀 */
prefix?: string;
/** 数值后缀 */
suffix?: string;
/** 数值为空时显示的文本 */
emptyText?: string;
/** 小数位数 */
decimals?: number;
/** 动画持续时间(毫秒) */
duration?: number;
/** 数值缩放系数,默认 0.01,即除以 100 */
valueScale?: number;
}>(), {
decimals: 2,
duration: 250,
valueScale: 0.01
});
const { value, prefix, suffix, emptyText, decimals, duration, valueScale } = toRefs(props);
const resolvedValue = computed(() => typeof value.value === "function" ? value.value() : value.value);
const scaledValue = computed(() => {
const currentValue = resolvedValue.value;
if (currentValue === undefined || currentValue === null) {
return currentValue;
}
return currentValue * valueScale.value;
});
</script>
+82 -38
View File
@@ -1,5 +1,13 @@
<template>
<span class="tui-animated-number">{{ displayValue }}</span>
<span v-if="hasValue || prefix || suffix || $slots.prefix || $slots.suffix || $slots.empty || emptyText" class="tui-animated-number">
<span v-if="$slots.prefix" class="prefix"><slot name="prefix" /></span>
<span v-else-if="prefix" class="prefix" v-text="prefix" />
<span v-if="hasValue" v-text="displayValue" />
<slot v-else-if="$slots.empty" name="empty" />
<span v-else-if="emptyText" class="empty" v-text="emptyText" />
<span v-if="$slots.suffix" class="suffix"><slot name="suffix" /></span>
<span v-else-if="suffix" class="suffix" v-text="suffix" />
</span>
</template>
<script lang="ts" setup>
@@ -8,34 +16,45 @@ defineOptions({
});
const props = withDefaults(defineProps<{
/** 目标数值 */
value: number;
/** 目标数值或数值 getter,为空时隐藏 */
value?: number | null | (() => number | null | undefined);
/** 数值前缀 */
prefix?: string;
/** 数值后缀 */
suffix?: string;
/** 数值为空时显示的文本 */
emptyText?: string;
/** 动画持续时间(毫秒),默认 1000ms */
duration?: number;
/** 小数位数,undefined 表示自动 */
decimals?: number;
/** 缓动函数类型 */
easing?: "linear" | "easeOut" | "easeInOut";
/** 是否启用千分位分隔符 */
thousands?: boolean;
/** 千分位分隔符,默认逗号 */
/** 分组方式:每 3 位、每 4 位或不分组,默认每 4 位 */
grouping?: "thousands" | "ten-thousands" | "none";
/** 自定义格式化函数,接收动画当前数值并返回显示文本 */
formatter?: (value: number) => string;
/** 自定义数字分隔符,默认逗号 */
separator?: string;
}>(), {
duration: 1000,
easing: "easeOut",
thousands: false,
separator: ","
grouping: "ten-thousands"
});
const { value, duration, decimals, easing, thousands, separator } = toRefs(props);
const { value, prefix, suffix, emptyText, duration, decimals, easing, grouping, formatter, separator } = toRefs(props);
// 数值是否有效
const resolvedValue = computed(() => typeof value.value === "function" ? value.value() : value.value);
const hasValue = computed(() => resolvedValue.value !== undefined && resolvedValue.value !== null);
const initialValue = resolvedValue.value ?? 0;
// 当前显示的数值
const currentValue = ref(value.value);
const currentValue = ref(initialValue);
// 格式化后的显示值
const displayValue = ref(formatNumber(value.value));
const displayValue = ref(hasValue.value ? formatNumber(initialValue) : "");
// 动画相关
let animationFrameId: number | null = null;
let startValue = value.value;
let startValue = initialValue;
let startTime: number | null = null;
/**
@@ -57,9 +76,9 @@ function ease(t: number, type: string): number {
}
/**
* 添加千分位分隔符
* 按指定间隔添加数字分隔符
*/
function addThousandsSeparator(numStr: string, sep: string): string {
function addDigitGroupSeparator(numStr: string, sep: string, groupSize: 3 | 4): string {
const parts = numStr.split(".");
const integerPart = parts[0];
const decimalPart = parts[1] ? "." + parts[1] : "";
@@ -67,9 +86,10 @@ function addThousandsSeparator(numStr: string, sep: string): string {
// 处理负号
const isNegative = integerPart.startsWith("-");
const absoluteInteger = isNegative ? integerPart.slice(1) : integerPart;
// 对整数部分添加千分位分隔符
const formatted = absoluteInteger.replace(/\B(?=(\d{3})+(?!\d))/g, sep);
const pattern = groupSize === 3
? /\B(?=(\d{3})+(?!\d))/g
: /\B(?=(\d{4})+(?!\d))/g;
const formatted = absoluteInteger.replace(pattern, sep);
return (isNegative ? "-" : "") + formatted + decimalPart;
}
@@ -78,8 +98,10 @@ function addThousandsSeparator(numStr: string, sep: string): string {
* 格式化数字
*/
function formatNumber(num: number): string {
if (formatter.value) {
return formatter.value(num);
}
let result: string;
if (decimals.value !== undefined) {
result = num.toFixed(decimals.value);
} else {
@@ -94,19 +116,25 @@ function formatNumber(num: number): string {
result = num.toString();
}
}
// 应用千分位分隔符
if (thousands.value) {
result = addThousandsSeparator(result, separator.value);
const separatorText = separator.value ?? ",";
if (grouping.value === "none") {
return result;
}
return result;
const groupSize = grouping.value === "thousands" ? 3 : 4;
return addDigitGroupSeparator(result, separatorText, groupSize);
}
/**
* 动画更新函数
*/
function animate(timestamp: number) {
const targetValue = resolvedValue.value;
if (targetValue === undefined || targetValue === null) {
animationFrameId = null;
startTime = null;
return;
}
if (startTime === null) {
startTime = timestamp;
}
@@ -116,15 +144,15 @@ function animate(timestamp: number) {
const easedProgress = ease(progress, easing.value);
// 计算当前值
currentValue.value = startValue + (value.value - startValue) * easedProgress;
currentValue.value = startValue + (targetValue - startValue) * easedProgress;
displayValue.value = formatNumber(currentValue.value);
if (progress < 1) {
animationFrameId = requestAnimationFrame(animate);
} else {
// 动画结束,确保显示精确的目标值
currentValue.value = value.value;
displayValue.value = formatNumber(value.value);
currentValue.value = targetValue;
displayValue.value = formatNumber(targetValue);
animationFrameId = null;
startTime = null;
}
@@ -145,20 +173,35 @@ function startAnimation() {
}
// 监听 value 变化
watch(value, (newValue) => {
watch(resolvedValue, (newValue) => {
if (newValue === undefined || newValue === null) {
if (animationFrameId !== null) {
cancelAnimationFrame(animationFrameId);
}
animationFrameId = null;
startTime = null;
return;
}
if (newValue !== currentValue.value) {
startAnimation();
} else {
displayValue.value = formatNumber(newValue);
}
});
// 监听 decimals 变化,立即更新显示格式
watch(decimals, () => {
displayValue.value = formatNumber(currentValue.value);
if (hasValue.value) {
displayValue.value = formatNumber(currentValue.value);
}
});
// 监听 thousands 和 separator 变化,立即更新显示格式
watch([thousands, separator], () => {
displayValue.value = formatNumber(currentValue.value);
// 监听分组方式、分隔符和格式化函数变化
watch([grouping, separator, formatter], () => {
if (hasValue.value) {
displayValue.value = formatNumber(currentValue.value);
}
});
// 组件卸载时清理动画
@@ -168,18 +211,19 @@ onUnmounted(() => {
}
});
// 初始化
onMounted(() => {
currentValue.value = value.value;
displayValue.value = formatNumber(value.value);
});
</script>
<style lang="less" scoped>
.tui-animated-number {
display: inline-block;
display: inline-flex;
align-items: baseline;
font-variant-numeric: tabular-nums;
font-feature-settings: "tnum";
.prefix,
.suffix {
font-size: 70%;
}
}
</style>
+1
View File
@@ -27,6 +27,7 @@ withDefaults(defineProps<{
font-size: .875rem;
text-align: center;
align-items: center;
flex-direction: column;
justify-content: center;
}
</style>
+3
View File
@@ -12,6 +12,7 @@ import MarkdownEditor from "./markdown-editor";
import PassTimeLabel from "./passtime-label";
import ContactNumber from "./contact-number";
import AnimatedNumber from "./animated-number";
import AnimatedAmount from "./animated-amount";
import DescriptionGrid from "./description-grid";
export default [
@@ -28,6 +29,7 @@ export default [
PassTimeLabel,
ContactNumber,
AnimatedNumber,
AnimatedAmount,
DescriptionGrid
];
@@ -47,6 +49,7 @@ export {
PassTimeLabel,
ContactNumber,
AnimatedNumber,
AnimatedAmount,
DescriptionGrid
};