防抖:当用户输入内容时,还没有输入完就频繁的触发事件,所以需要使用防抖来减少服务器压力
节流:当用户频繁的发起请求时,导致请求的次数太多,会给服务器造成压力,需要限制请求时间来减少服务器的压力
话不多说,实现防抖代码如下:
<template>
<div>
<input
type="text"
placeholder="请输入搜索内容"
@input="getVal"
v-model="val"
/>
</div>
</template>
<script>
export default {
data() {
return {
val: '',
time: null,//防抖
}
},
methods: {
getVal() {
if (this.time != null) {
clearTimeout(this.time)
}
this.time = setTimeout(() => {
console.log(this.val)
}, 3000)
},
},
}
</script>
<style lang="scss" scoped></style>
接下来就是处理节流
<div>
<input type="text" v-model="val" />
<button @click="toSearch">确定</button>
</div>
</template>
<script>
export default {
data() {
return {
val: '',
throttle: false, //节流
}
},
methods: {
toSearch() {
if (this.throttle) return
this.throttle = true
let t = setTimeout(() => {
console.log(this.val)
this.throttle = false
}, 3000)
},
},
}
</script>
<style lang="scss" scoped></style>
这上面两个都是简单防抖节流的处理,你还可以进行优化,也可以通过npm来下载lodash模块来实现防抖和节流