简体   繁体   English

VueJS如何观察一个值并在它改变时进行动画处理

[英]VueJS how to watch a value and animate when it changes

In my vuejs -application I want to animate a number/value when it changes.在我的vuejs ,我想在数字/值更改时对其进行动画处理。 The value is based on a response from the vuex -store.该值基于来自vuex的响应。

so I've got the animation running, but for some reason the animation loop is infinite and just continues all the time.所以我让 animation 运行,但由于某种原因,animation 循环是无限的,并且一直在继续。

data() {
  return {
     interval: false,
     hitsCount: 0
  }
},

watch: {
    hitsCount: function() {
       clearInterval(this.interval);

       this.interval = window.setInterval( function() {
            let change = this.hitsCount / 10;

            change = change >= 0 ? Math.ceil(change) : Math.floor(change);

            this.hitsCount = this.hitsCount + change;
        }.bind(this),20);
    }
}

the template is simply:模板很简单:

<div> {{hitsCount}} </div>

The value hitsCount comes from a request: hitsCount值来自一个请求:

this.$store.dispatch("store/data", {}).then(response => {
    this.hitsCount = response.total;
    .../
});

the value changes each time there is a new request.每次有新请求时,该值都会更改。

As mentioned before, the animation starts right away and keeps counting endlessly - what am I missing here?如前所述,animation 立即启动并不断计数 - 我在这里错过了什么?

Anyway, it's not good idea to watch property you are changing.无论如何,观察你正在改变的财产并不是一个好主意。 Divide it into two variables.把它分成两个变量。

data() {
  return {
    hitsCount: 0,
    hitsCountDisplay: 0
  }
},

watch: {
  hitsCount() {
    clearInterval(this.interval);

    if (this.hitsCount !== this.hitsCountDisplay) {
      let value = this.hitsCountDisplay;
      const change = (this.hitsCount - this.hitsCountDisplay) / 30;
      this.interval = setInterval(() => {
        value += change;
        this.hitsCountDisplay = Math.round(value);
        if (this.hitsCountDisplay === this.hitsCount) {
          clearInterval(this.interval);
        }
      }, 20);
    }          
  }
}

and

<div> {{hitsCountDisplay}} </div>

Here is a working example: https://jsfiddle.net/knvyrx8j/这是一个工作示例: https://jsfiddle.net/knvyrx8j/

You shouldn't update a property inside its watcher, this will cause an infinite loop, but you could run the animation inside the callback of your action dispatcher:您不应该在其观察者中更新属性,这将导致无限循环,但您可以在操作调度程序的回调中运行 animation:

this.$store.dispatch("store/data", {}).then(response => {
    let count = response.total;
    clearInterval(this.interval);

       this.interval = window.setInterval( function() {
            let change = count / 10;

            change = change >= 0 ? Math.ceil(change) : Math.floor(change);

            this.hitsCount = this.hitsCount + change;
        }.bind(this),20);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM