1
1
<script setup>
2
- import { ref , computed , onMounted } from " vue" ;
2
+ import { ref , computed , onMounted , watch } from " vue" ;
3
3
import { useNestedProp } from " ../useNestedProp" ;
4
4
import { dataLabel } from " ../lib" ;
5
5
import { useConfig } from " ../useConfig" ;
@@ -10,41 +10,58 @@ const props = defineProps({
10
10
config: {
11
11
type: Object ,
12
12
default () {
13
- return {}
13
+ return {};
14
14
}
15
15
},
16
16
dataset: {
17
17
type: Number ,
18
18
default: 0
19
- },
19
+ }
20
20
});
21
21
22
22
const FINAL_CONFIG = computed (() => {
23
23
return useNestedProp ({
24
24
userConfig: props .config ,
25
25
defaultConfig: DEFAULT_CONFIG
26
- })
26
+ });
27
27
});
28
28
29
29
const 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 );
31
31
32
- onMounted (( ) => {
32
+ const animateToValue = ( targetValue ) => {
33
33
const chunks = FINAL_CONFIG .value .animationFrames ;
34
- const chunk = props . dataset / chunks;
34
+ const chunk = Math . abs (targetValue - displayedValue . value ) / chunks;
35
35
36
36
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);
42
45
}
43
46
}
44
47
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 ) => {
45
61
if (FINAL_CONFIG .value .useAnimation ) {
46
- displayedValue .value = 0 ;
47
- animate ()
62
+ animateToValue (newValue);
63
+ } else {
64
+ displayedValue .value = newValue;
48
65
}
49
66
});
50
67
0 commit comments