簡體   English   中英

VueJS如何觀察一個值並在它改變時進行動畫處理

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

在我的vuejs ,我想在數字/值更改時對其進行動畫處理。 該值基於來自vuex的響應。

所以我讓 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);
    }
}

模板很簡單:

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

hitsCount值來自一個請求:

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

每次有新請求時,該值都會更改。

如前所述,animation 立即啟動並不斷計數 - 我在這里錯過了什么?

無論如何,觀察你正在改變的財產並不是一個好主意。 把它分成兩個變量。

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);
    }          
  }
}

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

這是一個工作示例: https://jsfiddle.net/knvyrx8j/

您不應該在其觀察者中更新屬性,這將導致無限循環,但您可以在操作調度程序的回調中運行 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