Number动画组件数值不更新怎么办?

a'ゞ世祥 阅读 5

我用 Vue 写了个数字滚动动画组件,但数据变了动画却不触发,一直是初始值。明明 props 传的 number 更新了,watch 也监听到了,可 DOM 上的数字就是不动。

试过加 key 强制刷新,也试过 nextTick 里手动调用动画函数,都不行。是不是我写法有问题?

<template>
  <div>{{ animatedValue }}</div>
</template>

<script>
export default {
  props: ['number'],
  data() {
    return { animatedValue: 0 }
  },
  watch: {
    number(newVal) {
      this.animateTo(newVal)
    }
  },
  mounted() {
    this.animatedValue = this.number
  }
}
</script>
我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
シ春凤
シ春凤 Lv1
代码放这了

看起来是你在 animateTo 方法里面没有正确更新 animatedValue。你需要确保 animateTo 方法在每次 number 变化时都能正确地更新 animatedValue。这里有个简单的例子,假设你想用一个简单的线性过渡效果:

export default {
props: ['number'],
data() {
return { animatedValue: 0 }
},
watch: {
number(newVal) {
this.animateTo(newVal)
}
},
mounted() {
this.animatedValue = this.number
},
methods: {
animateTo(target) {
let start = this.animatedValue
let change = target - start
let startTime = performance.now()
let duration = 500 // 动画持续时间,单位毫秒

function step(currentTime) {
let elapsedTime = currentTime - startTime
let progress = Math.min(elapsedTime / duration, 1)
this.animatedValue = start + change * progress
if (progress < 1) {
requestAnimationFrame(step.bind(this))
}
}

requestAnimationFrame(step.bind(this))
}
}
}


确保 animateTo 方法在 watch 监听到 number 变化时被正确调用,并且在 requestAnimationFrame 循环中更新 animatedValue。这样 DOM 才会重新渲染显示最新的值。
点赞
2026-03-20 15:11