vue-封装对话框

前言

开发后台管理系统时,经常需要使用对话框,封装成公共组件方便复用及管理

开始封装

以vue3+element-plus为例
src/components中新建diaLog.vue文件,使用具名插槽,让父组件决定渲染的内容

<template>
  <el-dialog
    v-model="visible"
    :width="width"
    @close="close"
  >
    <template #title>
      <slot name="title"></slot>
    </template>
    <slot name="content"></slot>
    <template #footer>
      <slot name="footer"></slot>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, toRefs, watch } from 'vue'
export default {
  name: 'DiaLog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: () => false
    },
    width: {
      type: String,
      default: '30%'
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      visible: false,
      width: props.width
    })
    const bindfn = {
      close() {
        emit('closeDiaLog')
      }
    }

    watch(() => props.dialogVisible,
      (val) => {
        state.visible = val
      }
    )

    return {
      ...toRefs(state),
      ...bindfn
    }
  }
}
</script>

父组件使用dialog

<template>
  <el-button @click="openDiaLog">dialog</el-button>

  <DiaLog :dialogVisible="dialogVisible" @closeDiaLog="closeDiaLog" :width="'30%'">
    <template #title>
      <div>
        <i class="el-icon-info"></i>
        自定义标题
      </div>
    </template>
    <template #content>
      <p>something</p>
    </template>
    <template #footer>
      <el-button @click="confirm">确定</el-button>
    </template>
  </DiaLog>
</template>

<script>
import { reactive, toRefs } from 'vue'
import DiaLog from './diaLog.vue'
import { ElMessage } from 'element-plus'
export default {
  name: 'HelloWorld',
  components: {
    DiaLog
  },
  setup() {
    const state = reactive({
      dialogVisible: false,
    })
    const bindfn = {
      openDiaLog() {
        state.dialogVisible = true;
      },
      closeDiaLog() {
        state.dialogVisible = false;
      },
      confirm() {
      	// 对话框确认后要执行的操作
        ElMessage.success('成功')
        state.dialogVisible = false;
      }
    }

    return {
      ...toRefs(state),
      ...bindfn
    }
  }
}
</script>

效果图

在这里插入图片描述
传入表格
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值