Number动画组件数值不更新是怎么回事?

长孙煜喆 阅读 2

我用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>
我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
A. 世杰
A. 世杰 Lv1
问题出在两点,watch没开immediate导致初始值不触发,还有定时器没清除会叠加冲突。直接改这样:

export default {
props: ['value'],
data() {
return {
displayValue: 0,
timer: null
}
},
watch: {
value: {
handler(newVal) {
this.animateTo(newVal)
},
immediate: true
}
},
methods: {
animateTo(target) {
if (this.timer) clearInterval(this.timer)
let current = this.displayValue
const step = (target - current) / 10
this.timer = setInterval(() => {
current += step
if (Math.abs(current - target) < 1) {
clearInterval(this.timer)
this.displayValue = target
this.timer = null
} else {
this.displayValue = Math.round(current)
}
}, 30)
}
}
}


关键是watch加immediate: true,还有每次动画前清掉上一个定时器,不然快速切数值时几个定时器同时跑就乱套了。
点赞
2026-03-02 18:03