vue函數防抖和節流


Vue函數防抖和節流https://zhuanlan.zhihu.com/p/72363385

 

<template>
 <div>
  <input type='text' v-model='value' @keydown = "hangleChange">
 </div>
</template>

<script>
function debounce(func, wait=1000){ let timeout; return function(event){ clearTimeout(timeout) timeout = setTimeout(()=>{ func.call(this, event) },wait) } } export default{ name:'', data(){ return{ value:'' } }, methods:{ hangleChange:debounce(function(e){ console.log(this.value) }) } } </script>


節流

<template>
 <div class="scroll" ref="previewText" @scroll.passive="fnScroll">
</template>
<script> export default{ name:'globalHospot', data(){ return{ count:0, fnScroll:() =>{} } }, methods: { fnHandleScroll (e) { console.log('scroll觸發了:' + this.count++, new Date()) }, fnThrottle(fn, delay, atleast){ //節流函數 let timer = null; let previous = null; return function(){ let now = +new Date() if(!previous) previous = now; if(atleast && now - previous > atleast){ fn(); previous = now; clearTimeout(timer) }else{ clearTimeout(timer) timer = setTimeout(()=>{ fn(); previous = null },delay) } } } }, created(){ this.fnScroll = this.fnThrottle(this.fnHandleScroll, 1000) //剛創建時執行  }, } </script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM