vue 實現防抖、節流


防抖、節流的概念是用戶高頻率的操作某一事件導致的性能問題。

 

防抖: 定義一個延遲執行的方法,如果在延遲時間內再調用該方法,則重新計算執行時間。

節流: 在規定的時間內執行方法。

 

應用場景:

用戶拖動滾動條可以用 節流 方式實現。

mounted() {
    window.addEventListener('scroll', this.scrollToTop)
  },
  methods: {
    scrollToTop() {
      clearTimeout(this.tiemID);
      this.tiemID = setTimeout(() => {
        console.log('執行節流函數');
      }, 1000);
    }
  }

input輸入關鍵字實時發送請求可以用 防抖 方式實現。

<template>
  <div>
    <input type="text" :value="value" @input="changeInput">
  </div>
</template>

<script>
  export default {
  data() {
    return {
      value: '',
      ms: 3000,
      timeID: ''
    };
  },
  methods: {
    changeInput(e) {
      this.value = e.target.value;
    }
  },
  watch: {
    value(newValue, oldValue) {
      if (newValue !== oldValue) {
        // 數據變化了,執行邏輯,這里做好防抖。
        this.ms = 3000;
        clearTimeout(this.timeID);
        this.timeID = setTimeout(() => {
          console.log(this.value);
        }, this.ms)
      }
    }
  }
}
</script>

<style lang='less' scoped>
  input {
    height: 60px;
    margin: auto;
    border: 1px solid #ccc;
  }
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM