首先,我们需要创建一个Vue组件来封装弹窗。在这个组件中,我们可以使用ElementUI的Dialog组件来实现弹窗的基本功能。
<template>
<el-dialog :visible.sync="visible" :title="title" :width="width" :before-close="beforeClose">
<slot></slot>
<div slot="footer">
<el-button @click="cancel">取消</el-button>
<el-button type="primary" @click="confirm">确定</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: 'MyDialog',
props: {
visible: {
type: Boolean,
default: false
},
title: {
type: String,
default: ''
},
width: {
type: String,
default: '50%'
}
},
methods: {
confirm() {
this.$emit('confirm')
},
cancel() {
this.$emit('cancel')
},
beforeClose(done) {
this.$emit('before-close', done)
}
}
}
</script>
在这个组件中,我们定义了三个props:visible、title和width,分别用于控制弹窗的显示、标题和宽度。我们还定义了三个方法:confirm、cancel和beforeClose,分别用于触发确定、取消和关闭事件。
为了让这个组件更加灵活,我们可以使用插槽来实现弹窗内容的自定义。在组件中,我们使用了一个slot标签来定义插槽,这样就可以在使用组件时,将需要显示的内容插入到这个插槽中。
为了让这个组件更加灵活,我们还可以使用事件来实现弹窗的交互。在组件中,我们定义了三个事件:confirm、cancel和before-close,分别用于触发确定、取消和关闭事件。在使用组件时,我们可以通过监听这些事件来实现自定义的交互逻辑。
最后,我们需要将这个组件导出,以便在其他地方使用。在组件的底部,我们使用export default语句将组件导出。
export default {
name: 'MyDialog',
props: {
visible: {
type: Boolean,
default: false
},
title: {
type: String,
default: ''
},
width: {
type: String,
default: '50%'
}
},
methods: {
confirm() {
this.$emit('confirm')
},
cancel() {
this.$emit('cancel')
},
beforeClose(done) {
this.$emit('before-close', done)
}
}
}
现在,我们就可以在其他地方使用这个组件了。例如,在一个Vue页面中,我们可以这样使用这个组件:
<template>
<div>
<el-button @click="showDialog">显示弹窗</el-button>
<my-dialog :visible="dialogVisible" :title="dialogTitle" @confirm="handleConfirm" @cancel="handleCancel" @before-close="handleBeforeClose">
<p>这是弹窗的内容</p>
</my-dialog>
</div>
</template>
<script>
import MyDialog from '@/components/MyDialog'
export default {
name: 'MyPage',
components: {
MyDialog
},
data() {
return {
dialogVisible: false,
dialogTitle: '弹窗标题'
}
},
methods: {
showDialog() {
this.dialogVisible = true
},
handleConfirm() {
// 处理确定事件
this.dialogVisible = false
},
handleCancel() {
// 处理取消事件
this.dialogVisible = false
},
handleBeforeClose(done) {
// 处理关闭事件
done()
}
}
}
</script>
在这个页面中,我们使用了MyDialog组件来实现弹窗的功能。我们通过监听MyDialog组件的confirm、cancel和before-close事件来实现自定义的交互逻辑。