以构建一个confirm组件为例

<template>
  <div>
    <!-- 蒙版 -->
    <transition name="fade">
      <div v-if="isVisible" class="mask" @click="close"></div>
    </transition>
    <!-- 内容 -->
    <transition name="upsd">
      <div class="detail" v-if="isVisible">
        <div class="title">
          {{ title }}
        </div>
        <div class="content">
          {{ content }}
        </div>
        <div class="btn-group">
          <m-button type="primary" @click="cancel">{{ cancelText }}</m-button>
          <m-button @click="confirm">{{ confirmText }}</m-button>
        </div>
      </div>
    </transition>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import mButton from '../button/index.vue'
const props = defineProps({
  title: String,
  content: String,
  cancelText: {
    type: String,
    default: '取消'
  },
  confirmText: {
    type: String,
    default: '确定'
  },
  cancelHandle: Function,
  confirmHandle: Function,
  close: Function
})
const duration = '0.3s'
const isVisible = ref(false)
const show = () => {
  isVisible.value = true
}
const close = () => {
  isVisible.value = false
  setTimeout(() => {
    // 通过render调用组件,销毁需在动画完成之后调用,否则动画无法显示
    props.close && props.close()
  }, parseFloat(duration.replace('s', '')) * 1000)
}
const cancel = () => {
  props.cancelHandle && props.cancelHandle()
  close()
}
const confirm = () => {
  props.confirmHandle && props.confirmHandle()
  close()
}
// 通过render调用必须在挂载之后再展示,否则动画无法展示
onMounted(() => {
  show()
})
</script>

在vue文件同级创建index.ts导出构建函数,如下

import { h, render } from 'vue'
import ConfirmComponent from './index.vue'
export const confirm = (
  title: string,
  content?: string,
  cancelText?: string,
  confirmText?: string
): Promise<void> => {
  return new Promise((resolve, reject) => {
    // 如果只传入一个参数,将该值赋予content
    if (title && !content) {
      content = title
      title = ''
    }
    // 销毁组件,把渲染的vnode去掉
    const close = (): void => {
      render(null, document.body)
    }
    const confirmHandle = (): void => {
      resolve()
    }
    const cancelHandle = (): void => {
      reject()
    }
    const vnode = h(ConfirmComponent, {
      title,
      content,
      cancelText,
      confirmText,
      cancelHandle,
      confirmHandle,
      close
    })
    render(vnode, document.body)
  })
}

调用时

confirm(
    'hdjfgdsjh',
    'nfsjakhfishdgfgfdhgfdhgfdhsgfjghfjhfgjhgfjfdghfgdfhgfhgj',
    '不了不了',
    '要的要的'
  )
    .then(() => {
      console.log('点击确定')
    })
    .catch(() => {
      console.log('点击取消')
    })
Logo

前往低代码交流专区

更多推荐