美文网首页
js事件节流和防抖以及在vue中的使用

js事件节流和防抖以及在vue中的使用

作者: 追梦_life | 来源:发表于2020-07-24 14:12 被阅读0次

节流(throttle)

原理
事件触发后,在指定时间内不会再触发,等到达这个指定时间后会再触发。简言之,就是让事件按一定的频率来触发,从而大大减少触发次数。

应用场景
窗口的 resize 事件,在改变浏览器窗口大小的过程中,resize是会不断执行的,频率非常之高,这时候就可以运用节流来控制resize事件的触发。

export function throttle(fn, wait=500){
  let last = 0
  return function (){
    let now = Date.now()
    if(now - last > wait){
      fn.apply(this, arguments)
      last = now
    }
  }
}

防抖(debounce)

原理
多次触发事件后,事件处理函数只执行一次,并且是在触发操作结束时执行。

应用场景
点击某个操作按钮向服务器发送操作请求,为了避免重复发起请求,可以用防抖来控制只向服务器请求一次

export function debounce(fn, wait=500){
  let timer = null
  return function (){
    let now = !timer
    timer && clearTimeout(timer)
    timer = setTimeout(()=>{
      timer = null
    }, wait)
    if(now){
      fn.apply(this, arguments)
    }
  }
}

在vue中使用

1、注册全局指令,具体代码如下:

// 注册全局节流指令
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);
  }
})

// 注册全局防抖指令
Vue.directive('debounce', {
  bind(el, binding) {
    let executeFunction
    if (binding.value instanceof Array) {
      const [func, timer] = binding.value;
      executeFunction = debounce(func, timer);
    } else {
      console.error(`debounce指令绑定的参数必须是数组,且需执行的事件类型或函数或时间间隔不能为空`)
      return
    }
    el.addEventListener('click', executeFunction);
  }
})

2、在main.js中导入

import './directives'

3、在组件中使用

<template>
  <div class="page-container">
    <div style="margin-top:40px;height:40px;"></div>
    <button v-throttle="[()=>throttleCallBack('throttle'),500]">
      点我(节流)
    </button>
    <button v-debounce="[()=>debounceCallBack('debounce'),500]">
      点我(防抖)
    </button>
  </div>
</template>

<script>
export default {
  methods: {
    throttleCallBack(val) {
      console.log('点击了节流按钮',val);
    },
    debounceCallBack(val) {
      console.log('点击了防抖按钮',val);
    },
  }
};
</script>

相关文章

网友评论

      本文标题:js事件节流和防抖以及在vue中的使用

      本文链接:https://www.haomeiwen.com/subject/oxrjlktx.html