vue实例中的节流

100 阅读1分钟

代码在main.js的vue实例中 ;

我把它放在了beforeCreate()钩子函数中;

也就是在以后的this实例中都可以调用这个方法;

        Vue.prototype.$globalTimer = null;
        //存放定时器Id的变量
        Vue.prototype.$throttle = (fn, delay) => {
            this.$globalTimer ? clearTimeout(this.$globalTimer) : '';
            //三元表达式判断定时器ID是否存在:
            //1,不存在 继续执行下方代码;
            //2,存在  清除已存在的定时器,使其不能执行 ,继续新建携带最新函数的定时器
            this.$globalTimer = setTimeout(() => fn(), delay);
        }