美文网首页
在vue中使用防抖和节流

在vue中使用防抖和节流

作者: 落花夕拾 | 来源:发表于2019-12-09 15:49 被阅读0次

    方法一:

    1、方法一:封装到utils.js中

    /**
     * //防抖---非立即执行版:
     *触发事件后函数不会立即执行,而是在 n 秒后执行,如果在 n 秒内又触发了事件,则会重新计算函数执行时间
    * */
    export function debounce1 (fn, delay) {
        let timer   = null;
        return function () {
        let args = arguments;
        let context = this;
            if (timer) {
                clearTimeout(timer);
            }
          timer = setTimeout(function () {
            fn.apply(context, args);
          }, delay);
        }
    }
    //防抖---立即执行版:
    /**
    * 立即执行版的意思是触发事件后函数会立即执行,* 然后 n 秒内不触发事件才能继续执行函数的效果。
    *   this:让 debounce 函数最终返回的函数 this 指向不变
     * arguments : 参数
     * */
    export function Debounce2(func,wait) {
      let timeout;
      return function () {
        let context = this;
        let args = arguments;
    
        if (timeout) clearTimeout(timeout);
    
        let callNow = !timeout;
        timeout = setTimeout(() => {
          timeout = null;
        }, wait)
        if (callNow) func.apply(context, args)
      }
    }
    
    /**
    * 时间戳版:
    * */
    
    export function _throttle(func, wait) {
      let previous = 0;
      return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
          func.apply(context, args);
          previous = now;
        }
      }
    }
    
    /**
     *
     * 定时器版:s
     *
     * */
    
    export function Throttle2(func, wait) {
      let timeout;
      return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null;
            func.apply(context, args)
          }, wait)
        }
    
      }
    }
    
    
    

    2、在vue组件中引入

    import {debounce} from '@/utils/utils.js'
    

    3、在组件中使用

    <el-col :span="8" style="margin-left: 20px">
                    <img class="VerificationCodeImg" v-bind:src="codeImg">
                    <div @click="getCaptcha" class="codeR">
                      <img src="./assets/image/refresh.svg">
                    </div>
                  </el-col>
    
    在methos中:
    methods:{
    getValidCaptcha (){
              this.$http({
                method:'post',
                params:{},
                url:'/api/json/capcha/captcha'
              }).
              then(res =>{
                if (res.data.code === 200) {
                  this.codeImg = 'data:image/png;base64,' + res.data.data.captchaImg
                  this.captchaId = res.data.data.captchaId
                } else {
                }
              });
    
          },
          getCaptcha:Debounce2(function () {
            this.getValidCaptcha()
          },5000),
    
    }
    

    [参考链接]https://blog.csdn.net/qq_42306443/article/details/102909376
    [参考链接]https://blog.csdn.net/qq_34764577/article/details/82952368

    方法二:使用自定义指令directive

    1、在main.js中全局注册

    //在持续触发事件的过程中,函数不会立即执行,并且每 2s 执行一次,在停止触发事件后,函数还会再执行一次。
    Vue.directive('throttle', {
      bind: (el, binding) => {
        let throttleTime = binding.value; // 节流时间
        if (!throttleTime) { // 用户若不设置节流时间,则默认2s
          throttleTime = 1000;
        }
        let cbFun;
        el.addEventListener('click', event => {
          if (!cbFun) { // 第一次执行
            cbFun = setTimeout(() => {
              cbFun = null;
            }, throttleTime);
          } else {
            event && event.stopImmediatePropagation();
          }
        }, true);
      },
    });
    
    

    2、在组件中使用:

       <el-col :span="8" style="margin-left: 20px">
                    <img class="VerificationCodeImg" v-bind:src="codeImg">
                    <div v-throttle @click="getValidCaptcha" class="codeR">
                      <img src="./assets/image/refresh.svg">
                    </div>
                  </el-col>
    
    methods:{
    getValidCaptcha (){
              this.$http({
                method:'post',
                params:{},
                url:'/api/json/capcha/captcha'
              }).
              then(res =>{
                if (res.data.code === 200) {
                  this.codeImg = 'data:image/png;base64,' + res.data.data.captchaImg
                  this.captchaId = res.data.data.captchaId
                } else {
                }
              });
    
          },
    }
    
    

    [参考链接]https://juejin.im/post/5ce3e400f265da1bab298359#heading-3

    相关文章

      网友评论

          本文标题:在vue中使用防抖和节流

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