基于vue,如何实现滚动条滚动到指定位置,对应位置数字进行tween特效

转载至
https://segmentfault.com/a/1190000015665620

实现代码

npm install tween.js --save-dev

2.引入tween.js

import TWEEN from 'tween.js'
// ***.vue,注意这里千万别在main.js中引入,否则运行会报:TWEEN is undefined,
// 这边存疑,不知道为什么在main.js中不执行

3.实现数字动画效果和监听滚动条

{{formatNum1}}

抵御攻击

export default {
  computed:{
    formatNum1(){
     let num = this.animatedNum1
      return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    }
  },
  data () {
    return {
     num1: 0,
     animatedNum1: 0
   }
  },
   watch: {
    num1: function(newValue, oldValue) {
      var vm = this
      function animate (time) {
        requestAnimationFrame(animate)
        TWEEN.update(time)
      }
      new TWEEN.Tween({ tweeningNumber: oldValue })
        .easing(TWEEN.Easing.Quadratic.Out)
        .to({ tweeningNumber: newValue }, 5000)
        .onUpdate(function () {
          vm.animatedNum1 = this.tweeningNumber.toFixed(0)   
          //toFixed(num):num代表小数点后几位
        })
        .start()
      animate()
    }
  },
  methods:{
    setAnimatedNum(){
      this.num1 = 3567892881
    },
    handleScroll(){      
      let windowH = document.body.clientHeight
      let docSrollTop = $(document).scrollTop()   //文档卷动值
      let clientH = $(window).height()  //视窗大小
      let sectionTop = $(".sectionBody").offset().top //动态文字模块距离文档头部的距离
      let sectionH = $(".sectionBody").height()
      if((docSrollTop + clientH - sectionTop) >= 0 
      && (docSrollTop - sectionTop - sectionH) <= 0){
        this.setAnimatedNum()
      }
    }
  },
  mounted(){
    this.handleScroll()
    window.addEventListener('scroll',this.handleScroll)
  }
}

项目地址 https://github.com/Mirror198829/cloud

你可能感兴趣的:(vue)