vue3 函数式封装confirm组件

在每次使用confirm组件时都要写个标签,再一顿操作,感觉很繁琐

今天我便花了一点时间封装了一个函数式调用的confirm组件

成果:

实现代码:

1. confirm组件

// confirm.vue
<script lang="ts" setup>
const props = withDefaults(
  defineProps<{
    title?: string
    content?: string
    confirmText?: string
    closeText?: string
    outClose?: boolean
    confirmFn: Function
    closeFn: Function
  }>(),
  {
    title: '提醒',
    content: '确认删除?',
    confirmText: '确认',
    closeText: '取消',
    outClose: true,
    confirmFn: () => {
      console.log('confirm')
    },
    closeFn: () => {
      console.log('cancel')
    }
  }
)

const show = ref(true)

const cancelPop = (value = false) => {
  if(value && props.outClose) {
    show.value = false
  }
}
</script>

2.实例化组件:

// confirm.js
import confirm from '@/components/confirm/confirm.vue'
import { createApp } from 'vue'
export default ({ title, content, confirmText, closeText, outClose }) => {
  return new Promise((reslove, reject) => {
    const instance = createApp(confirm, {
      title, 
      content, 
      confirmText, 
      closeText, 
      outClose,
      confirmFn: () => { 
        closeUnmount()
        reslove()
      },
      closeFn: () => {
        closeUnmount()
        reject()
      }
    })
  
    // 创建一个节点
    const vnode = document.createElement('div')
    // 添加到body元素上
    document.body.appendChild(vnode)
    // 实例挂载到节点上
    instance.mount(vnode)

    // 关闭状态
    // 注册实例并移除节点
    function closeUnmount() {
      instance.unmount(vnode)
      document.body.removeChild(vnode)
    }
  })
}

3.使用组件:

// 使用弹窗
const openConfirm = () => {
  confirm({title: '我是传进来的title', confirmText: '自定义确认文字'}).then(() => {
    console.log('点击确认了');
  }).catch(() => {
    console.log('点击取消了');
  })
}

  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值