防抖、节流的概念是用户高频率的操作某一事件导致的性能问题。
防抖: 定义一个延迟执行的方法,如果在延迟时间内再调用该方法,则重新计算执行时间。
节流: 在规定的时间内执行方法。
应用场景:
用户拖动滚动条可以用 节流 方式实现。
mounted() { window.addEventListener('scroll', this.scrollToTop) }, methods: { scrollToTop() { clearTimeout(this.tiemID); this.tiemID = setTimeout(() => { console.log('执行节流函数'); }, 1000); } }
input输入关键字实时发送请求可以用 防抖 方式实现。
<template>
<div>
<input type="text" :value="value" @input="changeInput">
</div>
</template>
<script>
export default {
data() {
return {
value: '',
ms: 3000,
timeID: ''
};
},
methods: {
changeInput(e) {
this.value = e.target.value;
}
},
watch: {
value(newValue, oldValue) {
if (newValue !== oldValue) {
// 数据变化了,执行逻辑,这里做好防抖。
this.ms = 3000;
clearTimeout(this.timeID);
this.timeID = setTimeout(() => {
console.log(this.value);
}, this.ms)
}
}
}
}
</script>
<style lang='less' scoped>
input {
height: 60px;
margin: auto;
border: 1px solid #ccc;
}
</style>
