Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

javascript - Debounce computed properties/getters in Vue

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

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

HTML:

<div id="app">
  <input v-model="text">
  <div>computed: {{ textComputed }} </div>
  <div>debounced: {{ textDebounced }} </div>
</div>

JS:

new Vue({
    el:'#app',
  data:{
    text:''
  },
  computed:{
    textDebounced: _.debounce(function(){
      return this.text
    },500),
    textComputed(){
        return this.text
    }
  }

})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I mention in my comment, debouncing is an inherently asynchronous operation, and so cannot return a value. Depending on your needs, you might want to debounce on the input side. There will be no difference between the value in text and that in textComputed, but if you v-model="textComputed", the value setting will be debounced.

If you specifically want a debounced version of a variable, mrogers has given a good solution.

var x = new Vue({
  el: '#app',
  data: {
    text: 'start'
  },
  computed: {
    textComputed: {
      get() {
        return this.text;
      },
      set: _.debounce(function(newValue) {
        this.text = newValue;
      }, 500)
    }
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<div id="app">
  <div>
    Debounced input:
    <input v-model="textComputed">
  </div>
  <div>
    Immediate input:
    <input v-model="text">
  </div>
  <div>computed: {{ textComputed }} </div>
  <div>debounced: {{ text }} </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...