好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Vue2.x-使用防抖以及节流的示例

utils:

?

// 防抖

export const debounce = (func, wait = 3000, immediate = true ) => {

  let timeout = null ;

  return function () {

   let context = this ;

   let args = arguments;

   if (timeout) clearTimeout(timeout);

   if (immediate) {

    var callNow = !timeout; //点击第一次为true 时间内点击第二次为false 时间结束则重复第一次

    timeout = setTimeout(() => {

     timeout = null ;

    }, wait); //定时器ID

    if (callNow) func.apply(context, args);

   } else {

    timeout = setTimeout( function () {

     func.apply(context, args);

    }, wait);

   }

  };

};

// 时间戳方案

export const throttleTime = (fn, wait = 2000) => {

  var pre = Date.now();

  return function () {

   var context = this ;

   var args = arguments;

   var now = Date.now();

   if (now - pre >= wait) {

    fn.apply(context, args);

    pre = Date.now();

   }

  };

};

// 定时器方案

export const throttleSetTimeout = (fn, wait = 3000) => {

  var timer = null ;

  return function () {

   var context = this ;

   var args = arguments;

   if (!timer) {

    timer = setTimeout( function () {

     fn.apply(context, args);

     timer = null ;

    }, wait);

   }

  };

};

vue中使用:

?

< template >

  < div class = "main" >

   < p >防抖立即执行</ p >

   < button @ click = "click1" >点击</ button >

 

   < br />

 

   < p >防抖不立即执行</ p >

   < button @ click = "click2" >点击</ button >

 

   < br />

 

   < p >节流时间戳方案</ p >

   < button @ click = "click3" >点击</ button >

 

   < br />

 

   < p >节流定时器方案</ p >

   < button @ click = "click4" >点击</ button >

  </ div >

</ template >

 

< script >

import { debounce, throttleTime, throttleSetTimeout } from './utils';

export default {

  methods: {

   click1: debounce(

    function() {

     console.log('防抖立即执行');

    },

    2000,

    true

   ),

   click2: debounce(

    function() {

     console.log('防抖不立即执行');

    },

    2000,

    false

   ),

   click3: throttleTime(function() {

    console.log('节流时间戳方案');

   }),

   click4: throttleSetTimeout(function() {

    console.log('节流定时器方案');

   })

  },

};

</ script >

 

< style scoped lang = "scss" >

* {

  margin: 0;

  font-size: 20px;

  user-select: none;

}

.main {

  position: absolute;

  left: 50%;

  transform: translateX(-50%);

  width: 500px;

}

button {

  margin-bottom: 100px;

}

</ style >

解释:

  防抖:

    立即执行版本:immediate为true,则点击第一次就执行,再继续点击则不执行,当wait时间结束后,再点击则生效,也就是只执行第一次。

    原理:

      点击第一次不存在timeoutID,并且callNow为true,则立即执行目标代码,点击第二次时存在了timeoutID,并且callNow为false,所以不执行目标代码,当wait时间结束后,把timeoutID设为null,则开始重复立即执行逻辑。

    不立即执行版:immediate为false,则点击第一次不执行,当wait时间结束后,才生效,也就是无论点击多少次,只执行最后一次点击事件

    原理:

      使用setTimeout延迟执行事件,如果多次触发,则clearTimeout上次执行的代码,重新开始计时,在计时期间没有触发事件,则执行目标代码。

  节流:

    连续触发事件时以wait频率执行目标代码。

效果:

以上就是Vue2.x-使用防抖以及节流的示例的详细内容,更多关于vue 防抖及节流的资料请关注服务器之家其它相关文章!

原文链接:https://HdhCmsTestcnblogs测试数据/jwyblogs/p/14454999.html

查看更多关于Vue2.x-使用防抖以及节流的示例的详细内容...

  阅读:41次