在Vue中反演计算的属性/ getter [英] Debounce computed properties/getters in Vue

查看:62
本文介绍了在Vue中反演计算的属性/ getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法去抖(lodash)计算属性或vuex getter。去抖动的函数总是返回undefined。

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

})


推荐答案

正如我在评论中提到的,debouncing是一种固有的异步操作,因此无法返回值。根据您的需要,您可能希望在输入方面进行辩护。 text 中的值与 textComputed 中的值没有区别,但是如果你 v-model =textComputed,值设置将被去抖动。

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.

如果您特别想要一个变量的去抖动版本, mrogers 给出了一个很好的解决方案。

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>

这篇关于在Vue中反演计算的属性/ getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆