【实战】Vue自定义防抖指令(最通俗易懂版)

680 阅读1分钟

防抖函数,默认200ms

/**
 * @author songzhiyong
 * @date 2020/08/03
 * @description click防抖,默认200ms
 */
export default {
  bind: (el, binding) => {
		if(typeof binding.value !== 'function'){
			throw new Error('v-debounce not a function')
		}
		let timer = null
		el.addEventListener('click', () => {
			if (timer) clearTimeout(timer)
			timer = setTimeout(() => {
				binding.value()
				timer = null
			}, 200)
		})
	}
}

使用方式

<el-button v-debounce="foo">查找</el-button>
import debounce from 'directive/debounce'
export default {
  directives: {    debounce  }
  methods: {
    foo() {
        console.log('点击了防抖函数')
    }
  }}

节流函数

/** * @author songzhiyong 
* @date 2020/08/03 
* @description click节流,默认500ms 
*/
export default {  
    bind: (el, binding) => {
        if(typeof binding.value !== 'function'){
          throw new Error('v-throttle not a function')
        }    
        let timer = null    
        el.addEventListener('click', () => {
          if (!timer) binding.value()
          timer = setTimeout(() => {
            clearTimeout(timer)
            timer = null
          }, 500)
    })
}}

使用方式

<el-button v-throttle="foo">查找</el-button>
import throttle from 'directive/throttle'
export default {
  directives: {    
    throttle
  },
  methods: {
    foo() {
        console.log('点击了节流函数')
    }
  }
}

直接v-debounce或者v-throttle绑定要触发的函数,不需要再@click触发。