vue封装全局的防抖节流函数

作者 : admin 本文共1084个字,预计阅读时间需要3分钟 发布时间: 2024-06-17 共1人阅读

1.在入口文件main.js中:

//防抖函数
export let debounce = (() => {
  let instances = []
  return function (fun, delay = 300) {
    //项目中,多个地方用到防抖,进行判断,每次调用全局的防抖函数,是否是同一块代码
    const stackLines = new Error().stack.split('
');
    let callerLine = stackLines[2];
    
    //判断数组中是否有了
    let index = instances.findIndex(item => {
      return item.callerLine == callerLine
    })
    if (index  {
      instance.timer = null
      instance.fun.apply(ctx, args)
    }, instance.delay)
  }
})()

//节流函数
export let throttle = (() => {
  let instances = []
  return function (fun, delay = 300) {
    const stackLines = new Error().stack.split('
');
    let callerLine = stackLines[2];
    let index = instances.findIndex(item => {
      return item.callerLine == callerLine
    })
    if (index  {
        instance.timeout = null;
        instance.fun.apply(this, args)
      }, instance.delay)
    }
  }
})()

Vue.prototype.$debounce = debounce;
Vue.prototype.$throttle = throttle;

2.页面中使用:


            

问一个是否的问题:

{{ answer2 }}

data() {
        return {
            question2: '',
            answer2: '请输入问题,否则我无法回答你!'
        };
    },

 

watch: {
        question2: function (newQuestion, oldQuestion) {
            this.answer2 = '请等待!';
            this.$debounce(this.getAnswer2, 1000);
        }
    },

 

getAnswer2: function() {
            if (this.question.indexOf('?') === -1) {
                this.answer2 = '请输入疑问句!';
                return;
            }else{
                this.answer2 = '请稍后...';
            setTimeout(() => {
                this.answer2 = '章总';
            }, 1000)
            }
            
        }

本站无任何商业行为
个人在线分享 » vue封装全局的防抖节流函数
E-->