自定义弹窗组件
图
使用ElementPlus时,弹窗是比较常用的组件,但是不做封装直接使用,很可能造成样式不统一,代码冗余等情况出现,所有最好还是做一个封装处理,统一使用封装的组件

组件

文件名为DialogComponent.vue,能统一调整所有弹窗的样式,实现与滚动条的结合

<!--弹窗组件-->
<template>
  <el-dialog
    v-model="mvOnOff"
    :title="title"
    :width="width"
    destroy-on-close
    @close="diaClose()"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false">
    <div>
      <div class="dialog-component-body-margin">
        <el-scrollbar max-height="70vh">
          <div class="dialog-component-body-padding">
            <slot name="body"/>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <template #footer>
      <slot name="footer"/>
    </template>
  </el-dialog>
</template>

<script setup>
import {watch, ref} from 'vue'

const props = defineProps({
  onOff: Boolean,
  title: String,
  width: Number,
})

const mvOnOff = ref(props.onOff)

watch(() => props.onOff, () => {
  mvOnOff.value = props.onOff
})

// 关闭回调,修复右上角关闭未更新v-model值问题
function diaClose() {
  console.log('关闭')
  mvOnOff.value = false
}
</script>

<style scoped lang="sass">
// 调整滚动条位置
.dialog-component-body-margin
  margin: -30px -20px
  .dialog-component-body-padding
    padding: 30px 20px
</style>

使用

<DialogComponent
    v-model:on-off="modifyData.dialog.flag"
    v-model:title="modifyData.dialog.title"
    v-model:width="modifyData.dialog.width">
    <template #body>
      <el-form
        ref="modifyRef"
        :model="modifyData.req"
        :rules="modifyData.rules"
        label-width="82">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="modifyData.req.name"/>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="modifyData.dialog.flag=false">取消</el-button>
      <el-button type="primary" @click="modifyDeal(modifyRef)" v-text="modifyData.dialog.btn"></el-button>
    </template>
  </DialogComponent>

弹窗垂直居中

// el-dialog 垂直居中
.el-dialog
  display: flex
  flex-direction: column
  margin: 0 !important
  position: absolute
  top: 50%
  left: 50%
  transform: translate(-50%, -50%)
  max-height: calc(100vh - 50px)
  max-width: calc(100% - 100px)
  // 调整圆角
  border-radius: 4px
// el-dialog 内容滚动
.el-dialog .el-dialog__body
  flex: 1
  overflow: auto