我在Vue模板中有一个简单的输入框,我想或多或少地使用debounce:
<input type="text" v-model="filterKey" debounce="500">
Run Code Online (Sandbox Code Playgroud)
但是,该debounce物业已在Vue 2中弃用.该建议仅说:"使用v-on:输入+第三方去抖功能".
你是如何正确实现它的?
我试图使用lodash,v-on:input和v-model来实现它,但我想知道是否可以不使用额外的变量.
在模板中:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
Run Code Online (Sandbox Code Playgroud)
在脚本中:
data: function () {
return {
searchInput: '',
filterKey: ''
}
},
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
Run Code Online (Sandbox Code Playgroud)
然后在computed道具中使用filterkey .
在回答我关于去抖动的问题后,我想知道vue.js和lodash/ underscore是否兼容此功能.答案中的代码
var app = new Vue({
el: '#root',
data: {
message: ''
},
methods: {
len: _.debounce(
function() {
return this.message.length
},
150 // time
)
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
确实在持续输入时执行我的函数,但是当它在一些不活动后最终执行时,输入function()似乎是错误的.
启动上面代码后的一个实际示例:
b),没有活动 - 长度更新(但错误地,见下文)看起来函数是在最后一个值上运行的message.
可能是在用值实际更新之前_.debounce处理vue.js 吗?data<input>
笔记:
lodash和underscore,具有相同的结果(用于debounce …