vue实现防抖和节流,有gif图分析

首先浅谈的是防抖和节流的区别:

防抖:

1.假设持续触发事件,在规定的时间内没有再次触发该事件,才会执行一次。如果它在规定的时间内再次触发了事件,时间就会重新计算,直到在规定的时间内没有触发该事件,才会执行。

节流:

1.在规定时间内只能执行一次,假如规定的时间是2秒,无论两秒内触发多少次事件,2秒内只能执行一次,4秒内执行两次

效果图:

 看了gif,是不是觉得又更加的清晰了它们之间的区别呀

common.js

/**
 * 防抖函数
 */
export function debounce(fn, delay = 500) {
  let timer = null;
  return function() {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
}
/**
 * 节流函数
 */
export function throttle(fn, delay = 500) {
  let timer = true;
  return function() {
    if (!timer) return
    timer = false
    setTimeout(() => {
      fn.apply(this, arguments)
      timer = true
    }, delay);
  }
}

组件代码:

<template>
  <div class="container">
    <h1>不经过任何处理</h1>
    <el-input @input="test" v-model="testInput"></el-input>
    <p>普通内容:{{setInput}}</p>
    <hr >
    <h1>防抖测试</h1>
    <el-input @input="testDebounce" v-model="testInputDebounce"></el-input>
    <p>防抖内容:{{setDebounce}}</p>
    <hr >
    <h1>节流测试</h1>
    <el-input @input="testThrottle" v-model="testInputThrottle"></el-input>
    <p>节流内容:{{setThrottle}}</p>
    <hr >
  </div>
</template>
<script>
  import {
    debounce,
    throttle
  } from '../utils/common.js'
  export default {
    data() {
      return {
        testInput: '',
        setInput: '',
        testInputDebounce: '',
        setDebounce:'',
        testInputThrottle: '',
        setThrottle:'',
      }
    },
    methods: {
      test() {
        this.setInput = this.testInput
      },
      // 防抖函数使用
      testDebounce: debounce(function() {
        this.setDebounce = this.testInputDebounce
      }),
      // 节流函数使用
      testThrottle: throttle(function() {
        this.setThrottle = this.testInputThrottle
      }, 1000)
    },
    created() {}
  }
</script>
<style>
  .container {
    background-color: white;
    width: 100%;
    height: 100%;
    padding: 20px;
  }
</style>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值