11<script setup>
2- import { ref , computed , onMounted } from " vue" ;
2+ import { ref , computed , onMounted , watch } from " vue" ;
33import { useNestedProp } from " ../useNestedProp" ;
44import { dataLabel } from " ../lib" ;
55import { useConfig } from " ../useConfig" ;
@@ -10,41 +10,58 @@ const props = defineProps({
1010 config: {
1111 type: Object ,
1212 default () {
13- return {}
13+ return {};
1414 }
1515 },
1616 dataset: {
1717 type: Number ,
1818 default: 0
19- },
19+ }
2020});
2121
2222const FINAL_CONFIG = computed (() => {
2323 return useNestedProp ({
2424 userConfig: props .config ,
2525 defaultConfig: DEFAULT_CONFIG
26- })
26+ });
2727});
2828
2929const formattedValue = ref (typeof props .dataset === ' number' ? props .dataset : props .dataset );
30- const displayedValue = ref (FINAL_CONFIG .value .useAnimation ? FINAL_CONFIG .value .animationValueStart : formattedValue .value );
30+ const displayedValue = ref (FINAL_CONFIG .value .useAnimation ? FINAL_CONFIG .value .animationValueStart : formattedValue .value );
3131
32- onMounted (( ) => {
32+ const animateToValue = ( targetValue ) => {
3333 const chunks = FINAL_CONFIG .value .animationFrames ;
34- const chunk = props . dataset / chunks;
34+ const chunk = Math . abs (targetValue - displayedValue . value ) / chunks;
3535
3636 function animate () {
37- displayedValue .value += chunk;
38- if (displayedValue .value < props .dataset ) {
39- requestAnimationFrame (animate)
40- } else {
41- displayedValue .value = props .dataset ;
37+ if (displayedValue .value < targetValue) {
38+ displayedValue .value = Math .min (displayedValue .value + chunk, targetValue);
39+ } else if (displayedValue .value > targetValue) {
40+ displayedValue .value = Math .max (displayedValue .value - chunk, targetValue);
41+ }
42+
43+ if (displayedValue .value !== targetValue) {
44+ requestAnimationFrame (animate);
4245 }
4346 }
4447
48+ animate ();
49+ };
50+
51+ onMounted (() => {
52+ if (FINAL_CONFIG .value .useAnimation ) {
53+ displayedValue .value = FINAL_CONFIG .value .animationValueStart ;
54+ animateToValue (props .dataset );
55+ } else {
56+ displayedValue .value = props .dataset ;
57+ }
58+ });
59+
60+ watch (() => props .dataset , (newValue ) => {
4561 if (FINAL_CONFIG .value .useAnimation ) {
46- displayedValue .value = 0 ;
47- animate ()
62+ animateToValue (newValue);
63+ } else {
64+ displayedValue .value = newValue;
4865 }
4966});
5067
0 commit comments