vue3中使用element-plus进行弹窗的封装代码
时间: 2024-05-02 20:21:54 浏览: 138
vue3 封装一个全局通用弹窗提示组件(利用js调用 类似于element)
5星 · 资源好评率100%
以下是一个简单的示例,演示如何使用 Vue3 和 Element Plus 封装一个弹窗组件:
```html
<template>
<el-dialog
:title="title"
:visible.sync="visible"
:width="width"
:before-close="beforeClose"
>
<slot></slot>
<div slot="footer" class="dialog-footer">
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="confirm">确定</el-button>
</div>
</el-dialog>
</template>
<script>
import { defineComponent } from 'vue'
import { ElDialog, ElButton } from 'element-plus'
export default defineComponent({
name: 'MyDialog',
components: { ElDialog, ElButton },
props: {
title: { type: String, default: '提示' },
visible: { type: Boolean, default: false },
width: { type: String, default: '30%' },
beforeClose: Function,
},
methods: {
confirm() {
// 触发确认事件,并关闭弹窗
this.$emit('confirm')
this.visible = false
},
},
})
</script>
<style>
/* 可选:自定义弹窗样式 */
.dialog-footer {
padding: 10px 20px;
text-align: right;
background-color: #f5f7fa;
border-top: 1px solid #ebeef5;
}
</style>
```
使用方法:
```html
<template>
<div>
<el-button @click="showDialog">打开弹窗</el-button>
<my-dialog
:visible.sync="dialogVisible"
@confirm="handleConfirm"
>
<!-- 弹窗内容 -->
<p>这是一个弹窗</p>
</my-dialog>
</div>
</template>
<script>
import { defineComponent, ref } from 'vue'
import MyDialog from '@/components/MyDialog.vue'
export default defineComponent({
components: { MyDialog },
setup() {
const dialogVisible = ref(false)
const showDialog = () => {
dialogVisible.value = true
}
const handleConfirm = () => {
// 处理确认事件
console.log('确认')
}
return { dialogVisible, showDialog, handleConfirm }
},
})
</script>
```
阅读全文