element-ui中el-dialog組件之destroy-on-close屬性


一. :destroy-on-close="true"的場景

有一種場景是我們有一個新建按鈕,要求每次我們重新打開el-dialog都是干凈的內容,所以我們每次點擊按鈕可能會用以下幾種辦法。

(1) 對使用的data數據進行重置

(2) 直接對包裹內容區域的dom(組件)使用v-if,銷毀/重建dom節點(組件)

(3) 使用:destroy-on-close="true",

但問題是輸入value值后,再重新打開內容還是存在。

<template>
  <div class="hello">
      <el-dialog
        title="彈框"
        :visible.sync="dialogVisible"
        :destroy-on-close="true"
        >
        <div>
          dialog
          <el-input v-model="value" placeholder="輸入測試的數據"></el-input>
        </div>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">確 定</el-button>
        </div>
      </el-dialog>
      <el-button @click="showDialog">點擊</el-button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data () {
    return {
       dialogVisible: true,
       value: '',
    }
  },
  methods: {
    showDialog () {
       this.dialogVisible = !this.dialogVisible
    }
  }
}
</script>


二 . 問題研究

  1. destroy-on-close="true",文檔說關閉時銷毀 Dialog 中的元素

  2. 由源碼得到該屬性會讓class為el-dialog的dom節點重新生成。

    (注意:key 的特殊 attribute 主要用在 Vue 的虛擬 DOM 算法,在新舊 nodes 對比時辨識 VNodes。如果不使用 key,Vue 會使用一種最大限度減少動態元素並且盡可能的嘗試就地修改/復用相同類型元素的算法。而使用 key 時,它會基於 key 的變化重新排列元素順序,並且會移除 key 不存在的元素。)

    // html部分    
    <div
            role="dialog"
            :key="key"
            aria-modal="true"
            :aria-label="title || 'dialog'"
            :class="['el-dialog', { 'is-fullscreen': fullscreen, 'el-dialog--center': center }, customClass]"
            ref="dialog"
            :style="style">...
    // js 部分
     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(() => { //重新生成class為el-dialog的dom
                  this.key++;
                });
              }
            }
          }
        },
    

三 . 怎么使用這個特點

所以你在當前組件使用時,聲明數據全都在my-content組件中,這樣當my-content被銷毀的時候屬於my-content的數據才會一起被銷毀

<template>
    <el-dialog>
       <my-content></my-content>
    </el-dialog>
</template>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM