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

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

然而,在Vue 2中debounce属性已被弃用。建议只说:“使用v-on:输入+第三方反弹功能”。

如何正确地实现它?

我尝试使用lodash, v-on:input和v-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)
}

然后在计算道具中使用过滤键。


当前回答

如果你可以将debounce函数的执行移动到某个类方法中,你可以使用utils-decorators lib中的decorator (npm install——save utils-decorators):

import {debounce} from 'utils-decorators';

class SomeService {

  @debounce(500)
  getData(params) {
  }
}

其他回答

请注意,我在接受的答案之前发布了这个答案。这不是 正确的。这只是从解决方案向前迈进了一步 的问题。我编辑了已接受的问题,以显示作者的实现和我使用的最终实现。


基于注释和链接迁移文档,我对代码做了一些更改:

在模板:

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

在脚本:

watch: {
  searchInput: function () {
    this.debounceInput();
  }
},

设置过滤器键的方法保持不变:

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

这看起来好像少了一个调用(只是v-model,而不是v-on:input)。

如果你正在使用Vue,你也可以使用v.model.lazy而不是debounce,但记住v.model.lazy并不总是有效,因为Vue限制它用于自定义组件。

对于自定义组件,您应该使用:value和@change.native

<b-input:value="data" @change。Native ="data = $event.target. "价值”> < / b-input >

 public debChannel = debounce((key) => this.remoteMethodChannelName(key), 200)

vue-property-decorator

如果你需要一个非常简约的方法,我做了一个(最初从vuejs-tips分叉也支持IE),可在这里:https://www.npmjs.com/package/v-debounce

用法:

<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />

然后在你的组件中:

<script>
export default {
  name: 'example',
  data () {
    return {
      delay: 1000,
      term: '',
    }
  },
  watch: {
    term () {
      // Do something with search term after it debounced
      console.log(`Search term changed to ${this.term}`)
    }
  },
  directives: {
    debounce
  }
}
</script>

这里有一种方法

... <输入v模型= " searchInput " > ... 设置(){ const searchInput = ref(null) const timeoutID = ref(null) watch(searchInput, (new, old) => { clearTimeout (timeoutID.value) timeoutID。value = setTimeout(() => { //调用搜索函数 }, 500) //毫秒 }) 返回{…} }