[英]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()
的輸入似乎是錯誤的。
啟動上述代碼后的一個實際示例:
b
),並且沒有活動 - 長度已更新(但錯誤,請參見下文) 看起來該函數是在message
的最后一個值上運行的。
會不會是_.debounce
在實際使用<input>
值更新之前處理了 vue.js data
?
筆記:
lodash
和underscore
測試,結果相同(對於debounce
和throttle
功能)。這是@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.