Debounce computed properties/getters in Vue

前端 未结 3 616
名媛妹妹
名媛妹妹 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条回答
  •  萌比男神i
    2020-12-11 01:55

    I don't have any insight as to why the debounce function doesn't work on a computed property. However, an alternative solution is to put the debounce on a function in the methods section and call it via a watch.

    https://jsfiddle.net/vsc4npv3/

    HTML:

    computed: {{ textComputed }}
    debounced: {{ debouncedText }}

    JavaScript:

    var x = new Vue({
        el:'#app',
      data:{
        text:'',
        debouncedText: ''
      },
      watch: {
        text: function (val) {
            this.debouncer();
        }
      },
      computed:{
        textComputed(){
            return this.text;
        }
      },
      methods: {
        debouncer: _.debounce(function(){
          this.debouncedText = this.text;
        },500)
      }
    
    })
    

提交回复
热议问题