首先,需要先写好一个防抖函数或节流函数
// 防抖函数 export function debounce(fn, delay){ let timeout = null return function(){ let args = arguments if(timeout) window.clearTimeout(timeout) timeout = setTimeout(() => { fn.apply(this, args) }, delay) } } // 节流函数 export function throttle(fn, wait){ let timeout = null return function(){ let args = arguments if(!timeout){ timeout = setTimeout(() => { timeout = null fn.apply(this, args) }, delay) } } }
然后,在vue文件中引用,并调用:
methods: { handleClick(){ this.debounce(this) }, debounce: debounce((vm) => { // do something,这里this不指向Vue实例,用vm传入 }, 1000), }
节流同理。