Element-UI 提供了一个 Dialog 组件,可以通过封装来减少代码量和提高组件的可复用性。下面是一个简单的封装 Dialog 的示例:

1. 创建一个 Dialog 组件:

<template>
  <el-dialog
    :title='title'
    :visible.sync='visible'
    :width='width'
    :fullscreen='fullscreen'
    :top='top'
    :modal='modal'
    :append-to-body='append'
    :lock-scroll='lock'
    :custom-class='customClass'
    :close-on-click-modal='closeOnClickModal'
    :close-on-press-escape='closeOnPressEscape'
    :show-close='showClose'
    @close='handleClose'
    @opened='handleOpened'
    @before-close='handleBeforeClose'
  >
    <slot></slot>
  </el-dialog>
</template>

<script>
export default {
  name: 'MyDialog',
  props: {
    title: String,
    visible: Boolean,
    width: String,
    fullscreen: Boolean,
    top: String,
    modal: Boolean,
    append: Boolean,
    lock: Boolean,
    customClass: String,
    closeOnClickModal: {
      type: Boolean,
      default: true
    },
    closeOnPressEscape: {
      type: Boolean,
      default: true
    },
    showClose: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },
    handleOpened() {
      this.$emit('opened')
    },
    handleBeforeClose(done) {
      this.$emit('before-close', done)
    }
  }
}
</script>

2. 在需要使用 Dialog 的组件中引入 Dialog 组件:

<template>
  <div>
    <el-button @click='visible = true'>显示 Dialog</el-button>
    <my-dialog :visible.sync='visible' title='提示' :width='400'>
      <div>这是一个 Dialog 组件</div>
    </my-dialog>
  </div>
</template>

<script>
import MyDialog from './MyDialog.vue'

export default {
  components: {
    MyDialog
  },
  data() {
    return {
      visible: false
    }
  }
}
</script>

通过简单的封装,可以更好地组织代码和提高代码的可维护性。

Element-UI Dialog 组件封装教程 - 代码简洁易用

原文地址: https://www.cveoy.top/t/topic/mUT3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录