Number动画组件数值不更新是怎么回事?
我用Vue写了个数字滚动动画组件,但数据变了视图却不更新,明明watch监听到了新值。是不是因为直接修改了DOM或者没触发响应式?试过nextTick也不行。
这是我的组件代码:
<template>
<span>{{ displayValue }}</span>
</template>
<script>
export default {
props: ['value'],
data() {
return { displayValue: 0 }
},
watch: {
value(newVal) {
this.animateTo(newVal)
}
},
methods: {
animateTo(target) {
// 简单的递增逻辑
let current = this.displayValue
const step = (target - current) / 10
const timer = setInterval(() => {
current += step
if (Math.abs(current - target) < 1) {
clearInterval(timer)
this.displayValue = target
} else {
this.displayValue = Math.round(current)
}
}, 30)
}
}
}
</script>
关键是watch加
immediate: true,还有每次动画前清掉上一个定时器,不然快速切数值时几个定时器同时跑就乱套了。