el-dialog设置组件关闭时销毁内容的属性destroy-on-close,会触发el-dialog中引入组件的生命周期函数

2,609 阅读1分钟

el-dialog中引入了组件A,当关闭el-dialog时,触发组件Acreated方法,这让我挠头啊

后面发现是destroy-on-close搞得鬼,源码中是给el-dialog的容器div添加了一个key,这个key的默认值是0

通过watch监听了visible属性,当visiblefalse时并且destroyOnClosetrue,则在$nextTick回调中对key++,以此来让容器内的内容重新渲染,代码如下:

data() {
  return {
    closed: false,
    key: 0
  };
},

watch: {
  visible(val) {
    if (val) {
      this.closed = false;
      this.$emit('open');
      this.$el.addEventListener('scroll', this.updatePopper);
      this.$nextTick(() => {
        this.$refs.dialog.scrollTop = 0;
      });
      if (this.appendToBody) {
        document.body.appendChild(this.$el);
      }
    } else {
      this.$el.removeEventListener('scroll', this.updatePopper);
      if (!this.closed) this.$emit('close');
      if (this.destroyOnClose) {
        this.$nextTick(() => {
          this.key++;
        });
      }
    }
  }
},