perf(components): perf count-to

This commit is contained in:
Soybean 2024-01-25 23:16:12 +08:00
parent 9cc7ee5c94
commit b2c61f0306

View File

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, nextTick, ref, watch } from 'vue';
import { TransitionPresets, useTransition } from '@vueuse/core'; import { TransitionPresets, useTransition } from '@vueuse/core';
defineOptions({ defineOptions({
@ -8,32 +8,42 @@ defineOptions({
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
startValue: 0, startValue: 0,
endValue: 2024, endValue: 2021,
duration: 1500,
autoplay: true, autoplay: true,
decimals: 0, decimals: 0,
prefix: '', prefix: '',
suffix: '', suffix: '',
separator: ',', separator: ',',
decimal: '.' decimal: '.',
useEasing: true,
transition: 'linear'
}); });
type TransitionKey = keyof typeof TransitionPresets;
interface Props { interface Props {
startValue?: number; startValue?: number;
endValue?: number; endValue?: number;
duration?: number;
autoplay?: boolean; autoplay?: boolean;
decimals?: number; decimals?: number;
prefix?: string; prefix?: string;
suffix?: string; suffix?: string;
separator?: string; separator?: string;
decimal?: string; decimal?: string;
useEasing?: boolean;
transition?: TransitionKey;
} }
const source = ref(0); const source = ref(props.startValue);
const transition = computed(() => (props.useEasing ? TransitionPresets[props.transition] : undefined));
const outputValue = useTransition(source, { const outputValue = useTransition(source, {
disabled: false, disabled: false,
duration: 1500, duration: props.duration,
transition: TransitionPresets.easeOutCubic transition: transition.value
}); });
const value = computed(() => formatValue(outputValue.value)); const value = computed(() => formatValue(outputValue.value));
@ -57,11 +67,16 @@ function formatValue(num: number) {
return prefix + x1 + x2 + suffix; return prefix + x1 + x2 + suffix;
} }
async function start() {
await nextTick();
source.value = props.endValue;
}
watch( watch(
[() => props.startValue, () => props.endValue], [() => props.startValue, () => props.endValue],
() => { () => {
if (props.autoplay) { if (props.autoplay) {
source.value = props.endValue; start();
} }
}, },
{ immediate: true } { immediate: true }