Bootstrap

封装 dialog 公共组件

前言

  • 在我们写项目的时候会用到各种框架,帮助我们快速高效的开发,element 是我们广泛使用的一种框架,弹窗组件在项目里也是很常见的一个组件,当项目需要使用大量弹框的情况下我们可以通过封装一个公共的弹框组件时=使代码更加高效简洁

封装 dialog 公共组件

  • 在 componets 文件夹里创建一个 dialog 文件,这里我将组件的大多数属性都用上了,只需要进行需求配置就行了

  • 子组件的代码

<el-dialog
  v-model="visible"
  :width="obj.dialogWidth"
  :top="obj.dialogTop"
  :before-close="handleClose"
  @closed="closed"
  :show-close="false"
  draggable
  center
  append-to-body
>
  <template #header="{ close }">
    <div class="my-header">
      <div class="title">{{ obj.dialogTitle }}</div>
      <div class="close" @click="close">
        <slot name="closeIcon"></slot>
      </div>
    </div>
  </template>
  <slot> </slot>
  <template #footer>
    <span v-if="obj.dialogIsFooter">
      <el-button @click="close">{{ obj.dialogCloseBtnText }}</el-button>
      <el-button @click="success">{{ obj.dialogSuccessBtnText }}</el-button>
    </span>
  </template>
</el-dialog>
<script setup>
import { ElMessageBox } from 'element-plus'
import { computed } from 'vue'

const props = defineProps({
  dialogObject: {
    default() {
      return {}
    },
    type: Object,
  },
})
const emit = defineEmits(['dialogSuccess', 'dialogClosed'])

const visible = computed(() => {
  return props.dialogObject.dialogVisible
})

const obj = {
  dialogVisible: props.dialogObject.dialogVisible || false,
  dialogTitle: props.dialogObject.title || '标题',
  dialogWidth: props.dialogObject.width || '30%',
  dialogTop: props.dialogObject.top || '12vh',
  dialogCloseBtnText: props.dialogObject.closeBtnText || '取消',
  dialogSuccessBtnText: props.dialogObject.successBtnText || '成功',
  dialogIsFooter: props.dialogObject.isFooter || false,
}

//取消按钮
const close = () => {
  props.dialogObject.dialogVisible = false
}

//确认的按钮
const success = () => {
  emit('dialogSuccess', false, 'success')
}

//关闭弹框的回调
const closed = () => {
  emit('dialogClosed')
}

//弹框关闭提醒
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('是否关闭弹窗')
    .then(() => {
      done()
      props.dialogObject.dialogVisible = false
    })
    .catch(() => {
      // catch error
    })
}
</script>
  • 父组件的代码
<template>
  <el-button type="danger" @click="btnClick">打开</el-button>
  <Dialog 
    class="dialogClass"
    :dialog-object="dialogObject"
    @dialogSuccess="dialogSuccess"
    @dialogClosed="dialogClosed"
  >
    <template #closeIcon>
      <el-button type="danger" :icon="Close" circle />
    </template>
    <template> 弹框内容 </template>
  </Dialog >
</template>
<script setup>
import Dialog from '@/components/dialog.vue'
import { reactive } from 'vue'
import { Close } from '@element-plus/icons-vue'

const dialogObject = reactive({
  dialogVisible: false,
  title: '标题',
  width: '90%',
  top: '12vh',
  successBtnText: '确定',
  closeBtnText: '取消',
  isFooter: true,
})
const btnClick = () => {
  dialogObject.dialogVisible = true
}
// 确定
const dialogSuccess = () => {
  dialogObject.dialogVisible = false
}
// 关闭弹窗的回调
const dialogClosed = () => {}
</script>
;