学过JavaScript的一些高级应用的同学,想必不会对JavaScript中的事件节流和防抖动陌生。我想应该都能随手甩出一段JavaScript代码实现节流和防抖动。但是,在实际开发中,写原生的JavaScript代码肯定是不会适应开发需求的。接下来,我们以Vue.js中如何很方便地使用事件节流和防抖动为例,在实际开发中运用一下~
事件节流则是指让事件在指定的一段时间内触发,且每次触发事件都会在这段时间的起始时间点开始执行,之后在这段时间内不会触发该事件。那么如何在Vue中方便的使用事件节流? 1. 定义事件节流函数
// 事件节流 export function throttle(fn, time) { let timer = null, context = this // 用于存储计时器 return function () { if (!timer) { // 如果此时不存在计时器 let arg = arguments fn.apply(context, arg) // 调用事件 timer = setTimeout(() => { // 开启计时器 // timer秒后 // 清除计时器 clearTimeout(timer) timer = null }, time) } } }2. 全局注册指令
Vue.directive('throttle', { bind(el, binding) { let executeFunction if (binding.value instanceof Array) { const [func, timer] = binding.value; executeFunction = throttle(func, timer); } else { console.error(`throttle指令绑定的参数必须是数组,且需执行的事件类型或函数或时间间隔不能为空`) return } el.addEventListener('click', executeFunction); } })3. main.js中引入
import './directives'4. 页面中使用
<template> <div> <button v-throttle="[() => { callBack('wjc') }, 3000]">click me! throttle</button> </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String }, methods: { callBack(name) { console.log(`my name is ${name}`) } } } </script>事件防抖动也是在指定的一段时间内触发,不同于事件节流的是它在这段时间结束时触发,在这个时间点结束之前该事件不会触发。 事件抖动函数定义
// 事件防抖动 export function debounce(fn, delay) { let timer = null, context = this return function() { if (!timer) { let arg = arguments timer = setTimeout(() => { fn.apply(context, arg) clearTimeout(timer) timer = null; }, delay) } }; }PS:指令注册使用方式同上。