如何在 Vue2 中实现去抖动?

新手上路,请多包涵

我在 Vue 模板中有一个简单的输入框,我想或多或少地像这样使用 debounce:

 <input type="text" v-model="filterKey" debounce="500">

但是 debounce 属性已 在 Vue 2 中被弃用。建议只说:“使用 v-on:input + 3rd 方去抖功能”。

您如何正确实施它?

我尝试使用 lodashv-on:inputv-model 来实现它,但我想知道是否可以不使用额外的变量。

在模板中:

 <input type="text" v-on:input="debounceInput" v-model="searchInput">

在脚本中:

 data: function () {
  return {
    searchInput: '',
    filterKey: ''
  }
},

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

filterkey 稍后在 computed 道具中使用。

原文由 MartinTeeVarga 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 769
2 个回答

我正在使用 debounce NPM 包并像这样实现:

 <input @input="debounceInput">

 methods: {
    debounceInput: debounce(function (e) {
      this.$store.dispatch('updateInput', e.target.value)
    }, config.debouncers.default)
}

使用 lodash 和问题中的示例,实现如下所示:

 <input v-on:input="debounceInput">

 methods: {
  debounceInput: _.debounce(function (e) {
    this.filterKey = e.target.value;
  }, 500)
}

原文由 Primoz Rome 发布,翻译遵循 CC BY-SA 4.0 许可协议

选项 1:可重用,无依赖

- 如果在您的项目中多次需要,建议使用

/helpers.js

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

/组件.vue

 <script>
  import {debounce} from './helpers'

  export default {
    data () {
      return {
        input: '',
        debouncedInput: ''
      }
    },
    watch: {
      input: debounce(function (newVal) {
        this.debouncedInput = newVal
      }, 500)
    }
  }
</script>

密码笔


选项 2:组件内,也没有部门

- 建议使用一次或在小型项目中使用

/组件.vue

 <template>
    <input type="text" v-model="input" />
</template>

<script>
  export default {
    data: {
        timeout: null,
        debouncedInput: ''
    },
    computed: {
     input: {
        get() {
          return this.debouncedInput
        },
        set(val) {
          if (this.timeout) clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            this.debouncedInput = val
          }, 300)
        }
      }
    }
  }
</script>

密码笔

原文由 digout 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题