Debounce computed properties/getters in Vue

前端 未结 3 618
名媛妹妹
名媛妹妹 2020-12-11 01:20

I can\'t seem to debounce (lodash) computed properties or vuex getters. The debounced functions always return undefined.

https://jsfiddle.net/guanzo/yqk0jp1j/2/

3条回答
  •  借酒劲吻你
    2020-12-11 01:54

    1. Simple
    2. No external dependencies (like _.debounce)
    3. Tailored for Vue
    import Vue from 'vue'
    
    // Thanks to https://github.com/vuejs-tips/v-debounce/blob/master/debounce.js
    function debounce(fn, delay) {
      var timeoutID = null
      return function () {
        clearTimeout(timeoutID)
        var args = arguments
        var that = this
        timeoutID = setTimeout(function () {
          fn.apply(that, args)
        }, delay)
      }
    }
    
    function debouncedProperty(delay) {
      let observable = Vue.observable({ value: undefined });
      return {
        get() { return observable.value; },
        set: debounce(function (newValue) { observable.value = newValue; }, delay)
      }
    }
    
    // component
    export default {
      computed: {
        myProperty: debouncedProperty(300),
      },
    }
    

提交回复
热议问题