记一次Vue很坑的设计?

从开始使用Vue到现在为止时间很短,说一下对于Vue的看法

1、代码简单,逻辑简单,通俗易懂;

2、对于typescript的支持较弱,可以说完全不支持,让行ts化让人写着很难受;

3、对于es6等更高级的语法支持的较弱,由于自身框架问题导致很多例如箭头函数等都不能使用;

4、代码太简单导致人人都会,没有难度而言;

lz最近遇到一个很傻的问题在这分享一下:

需求:在页面加载时设置全局监听事件,页面销毁时进行移除?

思路:

在mounted执行一个全局监听方法,在destroyed中进行移除对应方法;

第一版代码如下

public mounted (): void{
    window.addEventListener('scroll', throttle(500, ()=>{
        if (this.isElShow()) {
          this.btnShow = true;
        } else {
          this.btnShow = false;
        } 
    }, true);
  }

public destroyed (): void {
    window.removeEventListener('scroll', throttle(500, ()=>{
        if (this.isElShow()) {
          this.btnShow = true;
        } else {
          this.btnShow = false;
        } 
    }, true);
  }

知识:addEventListener,removeEventListener两个函数第二个参数要完全一致才能解除监听。

这样写会有一个问题,系统不会认为这是一个方法,因为声明了两次匿名函数,相当于两个方法,所以导致问题页面销毁监听还在,继续解决问题。

 public onScroll ():void {
    if (this.isElShow()) {
      this.btnShow = true;
    } else {
      this.btnShow = false;
    }
 }

public mounted (): void{
   window.addEventListener('scroll', throttle(500, this.onScroll), true);
}

public destroyed (): void {
   window.removeEventListener('scroll',  throttle(500, this.onScroll), true);
}

根据上面知识点,这种写法也是有问题的,继续改

 public onScroll = throttle( 500,()=> {
    if (this.isElShow()) {
      this.btnShow = true;
    } else {
      this.btnShow = false;
    }
  })

  public mounted(): void {
    window.addEventListener('scroll', this.onScroll, true);
  }

  public destroyed(): void {
    window.removeEventListener('scroll', this.onScroll, true);
  }

我们修改Listener部分参数,让第二个参数保持一致,你会发现箭头函数中的this不指向当前的类指向window了,vue不让使用箭头函数,哈哈哈,我笑了,继续改

最终版代码如下:

public onScroll(): void {
    if (this.isElShow()) {
      this.btnShow = true;
    } else {
      this.btnShow = false;
    }
  }

  public handleScroll = throttle(500, this.onScroll);

  public mounted(): void {
    window.addEventListener('scroll', this.onScroll, true);
  }

  public destroyed(): void {
    window.removeEventListener('scroll', this.onScroll, true);
  }

为了解决EventListener和Vue的问题我们把一个简单的代码要拆分成好几个方法最后才最终解决了问题;

posted @ 2021-05-07 11:17  程序員劝退师  阅读(158)  评论(0编辑  收藏  举报