2017-02-13 108 views
27

我有一个Vue公司的模板简单的输入框,我想或多或少地使用反跳这样的:如何在Vue2中实现去抖动?

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

然而debounce物业已经deprecated in Vue 2。该建议只说:“使用v-on:输入+第三方去抖功能”。

你如何正确实施它?

我试图实现它使用lodashV系列:输入V型,但我想知道是否有可能没有额外的变量做。

模板:

<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道具以后使用。

+1

试试这个HTTP:// stackoverflow.com/questions/41230343/how-to-temporize-the-analysis-of-an-input-field/41232221#41232221 – sobolevn

+2

我建议仔细阅读:https://vuejs.org/v2/guide/migration .html#debounce -Param-Attribute-for-v-model-removed –

+1

有一个e xample在指南中:https://vuejs.org/v2/guide/computed.html#Watchers – Bengt

回答

37

我使用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) 
} 
+3

谢谢你。我在其他一些Vue文档中找到了一个类似的例子:https://vuejs.org/v2/examples/index.html(降价编辑器) – sm4

+0

@ sm4感谢您的更新! –

+0

当页面上有多个组件实例时,建议的解决方案有问题。问题描述和解决方案在这里介绍:https://forum.vuejs.org/t/issues-with-vuejs-component-and-debounce/7224/10 – Valera

1

请注意,我在接受的答案之前发布了此答案。这不是 是正确的。这只是从 问题的解决方案中向前迈出的一步。我编辑了接受的问题,以显示作者的实施情况以及我使用过的最终实施情况。


根据意见和linked migration document,我做了对代码进行一些更改:

模板:

<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)。

+0

这不会为每次更改调用debounceInput()两次吗?'v-on:'会检测输入变化并调用去抖动,并且由于模型被绑定,searchInput的监视函数也会调用'debounceInput' ...对吗? – mix3d

+0

@ mix3d不要考虑这个答案。这只是我的调查,我不想提出这个问题。你很可能是对的。检查接受的答案。这是正确的,我编辑它以匹配问题。 – sm4

+0

我的错误...我没有意识到你已经回答了你自己的问题,哈! – mix3d