2017-02-13 113 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