vue简单的数字滚动动画

529 阅读1分钟

vue简单的数字滚动,使用transform:translateY()来实现滚动,简陋且粗暴

效果

1652851077297 00_00_00-00_00_30.gif

代码

	<div>
		<div class="record">
			<div v-for="(item, index) in list" :key="index" class="item border">
				<div
					v-for="(v, indexs) in 10"
					:key="indexs"
					class="item"
					:style="{ ...style(item) }"
				>
					{{ indexs }}
				</div>
			</div>
		</div>

		<div
			@click="randomNumber"
			style="
				width: 850px;
				height: 100px;
				background: #ccc;
				margin-top: 100px;
			"
		></div>
	</div>
</template>
<script>
export default {
	data() {
		return {
			// 父级传入
			quantity: 9, //默认9个
			delayed: true, //从零变化
			number: '123456789', //数字
			time: 2000, //过度时间
			timing: 'ease', //过度动画速度

			num: 0,
		}
	},
	computed: {
		numArr() {
			if (this.num) {
				return (this.num + '').split('')
			} else {
				return new Array(this.number.length).fill(0)
			}
		},
		list() {
			let arr = []
			let len = this.numArr.length
			if (this.quantity && this.quantity > len) {
				arr = [
					...new Array(this.quantity - len).fill(0),
					...this.numArr,
				]
			} else {
				arr = this.numArr
			}
			return arr
		},
	},
	methods: {
		randomNumber() {
			this.number = Math.floor(Math.random() * (999999999 - 1 + 1)) + 1
		},
		style(e) {
			return {
				transform: `translateY(-${e * 100}%)`,
				transition: this.time + 'ms',
				transitionTimingFunction: this.timing,
			}
		},
	},
	created() {
		if (this.delayed) {
			setTimeout(() => {
				this.num = this.number
			}, 1000)
		} else {
			this.num = this.number
		}
	},
	watch: {
		number: {
			handler(newValue, oldValue) {
				//newValue 新的值,oldValue变化前的值
				console.log(newValue, oldValue)
				this.num = newValue
			},
		},
	},
}
</script>
<style lang="scss" scoped>
* {
	touch-action: pan-y;
}
.record {
	display: flex;
	padding-top: 100px;
	width: 100%;
	align-items: center;
	justify-content: center;
}
.item {
	width: 60px;
	height: 80px;
	font-size: 50px;
	color: rgb(109, 160, 255);
	font-weight: 600;
	margin-right: 20px;
	text-align: center;
	line-height: 80px;
	overflow: hidden;
}
.border {
	border: 1px solid #ccc;
}
</style>

结尾

可封装为组件,

小白一个,干不动就回家喂猪