vue3自定义弹框组件,函数方式调用

缘由:项目要用到一个弹框,需要公共函数内调用。考虑封装成像 Element PlusElMessageBox.confirm 的方式调用,而不是直接在 template 中写组件的方式调用。

最小实现效果:
在这里插入图片描述
请添加图片描述

思路逻辑

实现

实现弹框 component

<template>
  <el-dialog
    v-model="visible"
    width="480"
    :title="props.title"
    :close-on-click-modal="false"
    @close="onClose()"
    @open="onOpen()"
  >
    <template #default>
      <el-form ref="formRef" :model="formData" inline-message label-width="120px">
        <template v-for="(item, index) in formData.barcodeList" :key="index">
          <el-form-item
            :label="`${$t('common.label')}(${index + 1})`"
            :prop="`barcodeList.${index}.barcode`"
            :rules="getRule(index)"
          >
            <div class="w-full flex items-center">
              <el-input v-model="item.barcode"></el-input>
              <el-button
                v-if="index !== 0"
                class="flex-center ml-10"
                type="plain"
                size="small"
                circle
                @click="onDelete(index)"
              >
                <i class="iconfont icon-delete ml-4 error-color"></i>
              </el-button>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <el-button type="primary" @click="addNewBarcode()">{{ $t('common.addBarCode') }}</el-button>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onClose()">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm(formRef)">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { computed, reactive, ref, PropType } from 'vue'
import { useI18n } from 'vue-i18n'

const { t: $t } = useI18n()

defineOptions({
  name: 'CompleteDialog',
})

const props = defineProps({
  message: String,
  title: String,
  onOpen: Function as PropType<() => void>,
  onCancel: Function as PropType<() => void>,
  onConfirm: Function as PropType<(data: any) => void>,
})
const emits = defineEmits(['submit'])

const visible = defineModel({ type: Boolean, default: false })

const formRef = ref<FormInstance>()
const formDataDefault = {
  barcodeList: [
    {
      barcode: '',
    },
  ] as any[],
}
const formData = reactive<typeof formDataDefault>({ ...formDataDefault })
const formRules = reactive<FormRules>({})
const getRule = (index?: number) => {
  return [{ required: true, message: $t('common.RequiredInput'), trigger: 'change' }]
}

const onDelete = (index: number) => {
  formData.barcodeList.splice(index, 1)
}

const addNewBarcode = () => {
  const len = formData.barcodeList.length
  formData.barcodeList.push({ barcode: '' })
}

const onOpen = () => {
  const { onOpen } = props
  if (onOpen) {
    onOpen()
  }
}

const onClose = () => {
  const { onCancel } = props
  if (onCancel) {
    onCancel()
  }
  formRef.value?.resetFields()
  Object.assign(formData, formDataDefault)
  visible.value = false
}

const submitForm = async (formEl?: FormInstance) => {
  if (!formEl) return

  await formEl.validate(async (valid: any) => {
    if (!valid) return false
    const result = { ...formData }
    emits('submit', result)
    if (props.onConfirm) {
      props.onConfirm(result)
    }
    onClose()
  })
}
</script>

<style lang="scss" scoped></style>

封装函数方式调用 index.tsx
因为用了 sx ,所以没有用 h 函数.如果没有用 jsx,需要用 h 函数创建 VNode

import { i18n, locale } from '@/lang/index'
import { createApp, ref, watch } from 'vue'
import ElementPlus from 'element-plus'
import CompleteDialog from './completeDialog.vue'

export const useConfirmCompleteDialog = <T extends any>(
  message?: string,
  title?: string
): Promise<T> => {
  return new Promise((resolve, reject) => {
    const div = document.createElement('div')
    document.body.appendChild(div)

    const app = createApp({
      setup() {
        const visible = ref(true)

        const close = () => {
          visible.value = false
        }

        const onConfirm = (data: any) => {
          resolve(data)
          close()
        }

        const onCancel = () => {
          reject()
          close()
        }

        watch(visible, newValue => {
          if (!newValue) {
            app.unmount()
            document.body.removeChild(div)
          }
        })

        return () => (
          <CompleteDialog
            modelValue={visible.value}
            onUpdate:modelValue={value => {
              visible.value = value
            }}
            message={message}
            title={title}
            onConfirm={onConfirm}
            onCancel={onCancel}
          ></CompleteDialog>
        )
      },
    })
    // 因为项目用了 i18n 国际化, ElementPlus UI组件,所以引入
    // 根据实际项目需要修改,不需要i18n,ElementPlus的可以取消,只需要注册自定义组件
    app.use(i18n).use(ElementPlus, { locale })
    app.component(CompleteDialog.name, CompleteDialog)
    app.mount(div)
  })
}

最小化实现:

vim myDialog/myDialog.vue

<template>
  <div v-if="visiable" class="my-dialog">
    <div class="mask" @click="onCancel"></div>
    <div class="dialog-content">
      <div class="dialog-title">{{ props.title }}</div>
      <div class="dialog-body">
        <div>{{ props.message }}</div>
        <slot>
        </slot>
      </div>
      <div class="dialog-footer">
        <div class="btn btn-cancel" @click="onCancel">Cancel</div>
        <div class="btn btn-confirm" @click="onConfirm">Confirm</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { PropType } from 'vue'


const props = defineProps({
  title: {
    type: String,
    default: 'Dialog Title'
  },
  message: String,
  onOpen: Function as PropType<() => void>,
  onCancel: Function as PropType<() => void>,
  onConfirm: Function as PropType<(data?: any) => void>,
})

const visiable = defineModel()
const onOpen = () => {
  props?.onOpen()
}
const onCancel = () => {
  props?.onCancel()
}
const onConfirm = () => {
  props?.onConfirm()
}
</script>

<style lang="scss" scoped>
.my-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.dialog-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  min-width: 300px;
  min-height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #fff;
  padding: 10px;
  border-radius: 10px;
}

.dialog-title {
  flex: 0 0 30px;
  font-size: 20px;
  border-bottom: 1px solid #eee;
}
.dialog-body {
  flex: 1;
  min-height: 24px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0 0;
  border-top: 1px solid #eee;
}
.btn {
  color: #fff;
  padding: 2px 10px;
  border: 1 solid #fff;
  border-radius: 4px;
  cursor: pointer;
}
.btn + .btn {
  margin-left: 10px;
}
.btn-cancel {
  background-color: #42b983;
  &:hover {
    background-color: #8ce6c2;
  }
}
.btn-confirm {
  background-color: #1d4ad4;
  &:hover {
    background-color: #8fa7f6;
  }
}
</style>

vim myDialog/index.tsx

import { createApp, ref, watch } from 'vue'
import MyDialog from './myDialog.vue'

export const useConfirmDialog = <T extends any>(
  message?: string,
  title?: string
): Promise<T> => {
  return new Promise((resolve, reject) => {
    const div = document.createElement('div')
    document.body.appendChild(div)

    const app = createApp({
      setup() {
        const visible = ref(true)

        const close = () => {
          visible.value = false
        }

        const onConfirm = (data: any) => {
          close()
          return resolve(data)
        }

        const onCancel = () => {
          close()
          return reject()
        }

        watch(visible, newValue => {
          if (!newValue) {
            app.unmount()
            document.body.removeChild(div)
          }
        })

        return () => (
          <MyDialog
            modelValue={visible.value}
            onUpdate:modelValue={value => {
              visible.value = value
            }}
            message={message}
            title={title}
            onConfirm={onConfirm}
            onCancel={onCancel}
          ></MyDialog>
        )
      },
    })
    app.component(MyDialog.name, MyDialog)
    app.mount(div)
  })
}

demo调用

<template>
  <div>
    <button @click="showMyDialog">showMyDialog</button>
  </div>
</template>
<script setup lang="ts">
import { useConfirmDialog } from './myDialog'
function showMyDialog() {
  useConfirmDialog('hello myDialog', 'title dialog').then(() => {
    console.log('myDialog confirm')
  }).catch(() => {
    console.log('myDialog cancel')
  })
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值