v-countup 数字滚动
介绍
v-countup 指令用于创建数字滚动动画效果,支持指定目标数值或使用元素内容作为目标值,支持小数位滚动。
基础用法
当不指定 value 时,会使用元素的文本内容作为目标值。
3000
查看代码
vue
<template>
<div class="demo-block">
<span v-countup>3000</span>
</div>
</template>
<style scoped>
.demo-block {
padding: 20px;
border: 1px solid var(--vp-c-divider);
border-radius: 4px;
display: flex;
align-items: center;
gap: 10px;
background-color: var(--vp-c-bg);
}
.demo-block span {
font-size: 24px;
font-weight: bold;
color: var(--vp-c-text-1);
}
</style>
注意
请确保元素的文本内容为有效的数字。
响应式用法
查看代码
vue
<template>
<div class="demo-block">
<span v-countup="count"></span>
<a-button type="primary" shape="round" size="large" @click="updateCount"> 更新数值 </a-button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(3001)
const updateCount = () => {
count.value = Math.floor(Math.random() * 5000)
}
</script>
<style scoped>
.demo-block {
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
display: flex;
align-items: center;
gap: 10px;
}
.demo-block span {
font-size: 24px;
font-weight: bold;
color: #2c3e50;
}
</style>
链式传参
持续时间 (duration)
1000小数位数 (decimals)
1500.99起始值 (startVal)
5173组合使用
5173.99查看代码
vue
<template>
<div class="demo-block">
<div class="modifier-example">
<h4>持续时间 (duration)</h4>
<span v-countup.duration-3>1000</span>
</div>
<div class="modifier-example">
<h4>小数位数 (decimals)</h4>
<span v-countup.decimals-2>1500.99</span>
</div>
<div class="modifier-example">
<h4>起始值 (startVal)</h4>
<span v-countup.startVal-3000>5173</span>
</div>
<div class="modifier-example">
<h4>组合使用</h4>
<span v-countup.duration-3.decimals-2.startVal-100>5173.99</span>
</div>
</div>
</template>
<style scoped>
.demo-block {
display: flex;
flex-direction: column;
gap: 20px;
}
.modifier-example {
padding: 10px;
border: 1px solid #eee;
border-radius: 4px;
}
.modifier-example h4 {
margin: 0 0 10px 0;
color: #666;
font-size: 14px;
}
span {
font-size: 24px;
color: #409eff;
}
</style>
API
指令值
属性名 | 说明 | 类型 | 是否必选 | 默认值 |
---|---|---|---|---|
value | 目标数值 | number | { value: number } | 元素内容 |
修饰符
属性名 | 说明 | 类型 | 是否必选 | 默认值 |
---|---|---|---|---|
duration | 动画持续时间(秒) | number | 2 | |
decimals | 小数位数,用于控制小数点后的位数 | number | 0 | |
startVal | 起始值 | number | 0 |
注意事项
注意
- 当不指定 value 时,会使用元素的文本内容作为目标值,请确保内容为有效的数字。
- 支持响应式数据绑定,当绑定值发生变化时会自动更新动画。
- 动画使用 requestAnimationFrame 实现,保证了较好的性能和流畅度。
- 如果目标值不是有效的数字,指令将不会执行动画并在控制台输出警告。