簡體   English   中英

Vue.js 和 debounce (lodash/underscore) 兼容嗎?

[英]Are Vue.js and debounce (lodash/underscore) compatible?

回答關於去抖動的問題后,我想知道 vue.js 和lodash / underscore是否與此功能兼容。 答案中的代碼

 var app = new Vue({ el: '#root', data: { message: '' }, methods: { len: _.debounce( function() { return this.message.length }, 150 // time ) } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script> <script src="https://unpkg.com/underscore@1.8.3"></script> <!-- undescore import --> <div id="root"> <input v-model="message">Length: <span>{{ len() }}</span> </div>

當有連續輸入時確實會執行我的函數,但是當它在一些不活動后最終執行時, function()的輸入似乎是錯誤的。

啟動上述代碼后的一個實際示例:

  1. 快速的字符序列,然后沒有活動:

在此處輸入圖像描述

  1. 添加了一個額外的字符 ( b ),並且沒有活動 - 長度已更新(但錯誤,請參見下文)

在此處輸入圖像描述

  1. 用 Backspace 快速擦除所有字符:

在此處輸入圖像描述

  1. 添加一個字符:

在此處輸入圖像描述

看起來該函數是在message的最后一個值上運行的。

會不會是_.debounce在實際使用<input>值更新之前處理了 vue.js data

筆記:

  • 使用lodashunderscore測試,結果相同(對於debouncethrottle功能)。
  • 我還在 JSFiddle 上對其進行了測試,以防對 SO 片段有一些干擾

這是@saurabh 版本的改進版本。

 var app = new Vue({ el: '#root', data: { message: '', messageLen: 0 }, methods: { updateLen: _.debounce( function() { this.messageLen = this.message.length }, 300) } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script> <script src="https://unpkg.com/underscore@1.8.3"></script> <!-- undescore import --> <div id="root"> <input v-model="message" v-on:keyup="updateLen">Length: <span>{{ messageLen }}</span> </div>

為什么會發生這種情況是因為 Vue 只有在方法中使用的 vue 變量發生變化時才會調用方法,如果 vue 變量沒有變化,則不會觸發這些方法。

同樣在這種情況下,一旦我們停止輸入,它將繼續顯示上次調用方法的輸出,並且只有在您再次輸入輸入后才會再次顯示。

如果您不想在所有輸入上調用函數,則可以使用另一種方法,您可以在 blur事件上調用方法,因此只有當焦點超出輸入字段時才會調用方法,如下所示:

 var app = new Vue({ el: '#root', data: { message: '', messageLen: 0 }, methods: { updatateLen: function() { this.messageLen = this.message.length } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script> <script src="https://unpkg.com/underscore@1.8.3"></script> <!-- undescore import --> <div id="root"> <input v-model="message" v-on:blur="updatateLen">Length: <span>{{ messageLen }}</span> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM