通常前端会有这种写法:

this.scroll && this.scroll.xxx

这样的写法的目的,是首先判断this.scroll是否为null,如果是,则不会执行后面的代码,如果不是,则会执行后面的代码,相比如下的写法,会更加简洁:

    if(this.scroll){
       this.scroll.xxx;
    }
防抖函数

对于refresh非常频繁的问题,进行防抖操作

  • 防抖debounce,节流throttle
  • 防抖函数起作用的过程:
    • 如果我们直接执行refresh,那么refresh函数会被直接(频繁)执行
    • 可以将refresh函数传入到debounce函数种,生成一个新的函数
    • 之后在调用非常频繁的时候,就使用新生成的函数
    • 新生成的函数并不会被频繁的调用,如果下一次执行来的非常快,会取消上一次的函数调用
    // 防抖函数参考代码
    mounted(){
        const refresh = this.debounce(this.$refs.scroll.refresh, 200);
        this.$bus.$on('itemImgLoad', () => {
            refresh();
        })
    },
    methods: {
        // 防抖函数
        debounce(func, delay){
            let timer = null;
            return function (...args){
                // 取消已有的定时器(其实可以理解为,取消了上一次的函数调用)
                if(timer) clearTimeout(timer);
                timer = setTimeout(() => {
                    func.apply(this, args);
                }, delay)
            }
        }
    }

相关文章:

  • 2022-12-23
  • 2022-02-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-01
猜你喜欢
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-04
相关资源
相似解决方案