https://lodash.com/docs/4.17.4#debounce
--Debouncing 曾经被用来控制 Ajax 请求及其它高耗任务的频率。Vue 中v-model的 debounce 属性参数使得在一些简单情况下非常容易实现这种控制。但实际上,这是控制了 状态更新 的频率,而不是控制高耗时任务本身。这是个微小的差别,但是会随着应用增长而显现出局限性。 例如在设计一个搜索提示时的局限性: 使用 debounce 参数,便无法观察 “Typing” 的状态。因为无法对输入状态进行实时检测。然而,通过将 debounce 与 Vue 解耦,可以仅仅只延迟我们想要控制的操作,从而避开这些局限性: 通过使用 lodash 或者其它库的 debounce 函数, 我们相信 debounce 实现是一流的, 并且可以随处使用它,不仅仅是在模板中。--
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>
<div id="debounce-search-demo">
<input v-model="searchQuery" placeholder="Type something">
<strong>{{ searchIndicator }}</strong>
</div>
new Vue({
el: '#debounce-search-demo',
data: {
searchQuery: '',
searchQueryIsDirty: false,
isCalculating: false
},
computed: {
searchIndicator: function () {
if (this.isCalculating) {
return '⟳ Fetching new results'
} else if (this.searchQueryIsDirty) {
return '... Typing'
} else {
return '✓ Done'
}
}
},
watch: {
searchQuery: function () {
this.searchQueryIsDirty = true
this.expensiveOperation()
}
},
methods: {
// 这是 debounce 实现的地方。
expensiveOperation: _.debounce(function () {
this.isCalculating = true
setTimeout(function () {//setTimeout模拟ajax
this.isCalculating = false
this.searchQueryIsDirty = false
}.bind(this), 1000)
}, 500)
}
})