data中定义timer:null
if(this.timerId){
clearTimeout(this.timerId)
}
this.timerId = setTimeout(()=>{
this.$emit('change_tree_plant', data, node.level) //要执行的方法
this.timerId = null //清空定时器
},2000)
短时间内多次发送重复请求
<template>
<div>
<button @click="sendReq">button1</button>
<button @click="sendReq">button2</button>
<p>{{content}}</p>
</div>
</template>
<script>
export defalut {
data(){
return {
timer : null, //定义定时器
counter : 0, //计时器
content : '', //响应数据内容
}
}
}
methods : {
clearTimerout(this.timer); //清除没执行的timer定时器
this.counter++;
this.timer = setTimeout(()=>{//定义一个timer定时器,延迟执行ajax请求
this.$axios.get(`/xxxx?id=1&counter=${this.counter}`).then(resonse=>{
if(response.counter < this.counter){ //后台返回的counter字段值与前端存储的计数器值做比较,如果不相等,这说明返回的数据不是用户最后一次操作的数据。因此不渲染数据到DOM上
return;
}
this.content = response.content;
})
}, 500)
}
</script>