您现在的位置是:首页 > 网站制作 > vue.js心得vue.js心得
vue防抖,节流函数
蒙xs2022-08-08【vue.js心得】人已围观
简介防抖函数 频繁触发再次触发需要倒计时结束才执行请求,或者函数
节流函数 短时间多次频繁点击只执行最后一次
1.测试防抖函数
2.测试代码节流
<template>
<div class="Index">
<input v-model="value" @keyup="handleChange" />
</div>
</template>
<script>
export default {
name: "Index",
data(){
return{
value:"",
counttimes: null
}
},
created() {
},
methods: {
handleChange() {
if(this.counttimes){
clearTimeout(this.counttimes)
}
this.counttimes = setTimeout(() => {
//调用接口
console.log('调用接口')
}, 1000);
},
beforeDestroy(){
clearTimeout(this.counttimes);
},
},
};
</script>
<div class="Index">
<input v-model="value" @keyup="handleChange" />
</div>
</template>
<script>
export default {
name: "Index",
data(){
return{
value:"",
counttimes: null
}
},
created() {
},
methods: {
handleChange() {
if(this.counttimes){
clearTimeout(this.counttimes)
}
this.counttimes = setTimeout(() => {
//调用接口
console.log('调用接口')
}, 1000);
},
beforeDestroy(){
clearTimeout(this.counttimes);
},
},
};
</script>
2.测试代码节流
<template>
<div class="Index">
<button @click="testClick">确定</button>
</div>
</template>
<script>
export default {
name: "Index",
data(){
return{
timer: null
}
},
created() {
},
methods: {
fnThrottle (method, delay, duration) {
var that = this;
var timer = this.timer;
var begin = new Date().getTime();
return function(){
var context = that;
var args = arguments;
var current = new Date().getTime();
clearTimeout(timer);
if(current-begin>=duration){
method.apply(context,args);
begin=current;
}else{
that.timer=setTimeout(function(){
method.apply(context,args);
},delay);
}
}
},
testClick(){
this.fnThrottle(this.add, 1000, 1000)();
},
add(){
console.log('触发了')
}
},
};
</script>
<div class="Index">
<button @click="testClick">确定</button>
</div>
</template>
<script>
export default {
name: "Index",
data(){
return{
timer: null
}
},
created() {
},
methods: {
fnThrottle (method, delay, duration) {
var that = this;
var timer = this.timer;
var begin = new Date().getTime();
return function(){
var context = that;
var args = arguments;
var current = new Date().getTime();
clearTimeout(timer);
if(current-begin>=duration){
method.apply(context,args);
begin=current;
}else{
that.timer=setTimeout(function(){
method.apply(context,args);
},delay);
}
}
},
testClick(){
this.fnThrottle(this.add, 1000, 1000)();
},
add(){
console.log('触发了')
}
},
};
</script>
Tags:
很赞哦! ()