- 使用defineComponent 定义一个组件
- 使用h函数渲染组件
- 使用createApp 创建组件实例
- 使用mount 插入组件
- 使用unmount移除组件
定义组件
export function Dialog(config) {
const id = 'MwDialog'
const Comp = defineComponent({
props: {
config: {
type: Object,
default: () => ({
})
}
},
setup(props) {
const {
showCancel = true, title = '', content = '', confirmCallback = () => {
}, cancelCallBack = () => {
} } = props.config
const state = reactive({
class: 'mw-dialog bounce-enter' })
const onCancel = () => {
console.log('点击了取消')
removeComp(dialogRef, id)
cancelCallBack()
}
const onConfirm = () => {
console.log('点击了确认')
removeComp(dialogRef, id)
confirmCallback()
}
return () => h('div', {
class: state.class }, [
h('div', {
class: 'dialog' }, [
h('div', {
class: 'dialog-header' }, title),
h('div', {
class: 'dialog-content' }, [h('div', {
class: 'dialog-message' }, content),]),
h('div', {
class: 'dialog-footer' }, [
showCancel ? h('div', {
onClick: onCancel, class: 'dialog-button dialog-button-cancel' }, '取消') : null,
h('div', {
onClick: onConfirm, class: 'dialog-button dialog-button-confirm' }, '确认')]),
])]
)
}
});
appendComp(dialogRef, Comp, id, config)
}
export function appendComp(ref, Comp, id, config) {
const parentId = 'mwPage'
const div = document.createElement('div');
div.setAttribute('id', id)
const page = document.getElementById(parentId)
page?.appendChild(div);
const app = createApp(Comp, {
config});
app.mount(div);
}
export function removeComp(ref, id) {
const div = document.getElementById(id)
div?.remove()
ref?.unmount()
}
调用组件
var title = "确认框";
var msg = "我是一个confirm类型的弹窗(确认框)~点击按键改变标签组件文字哦!";
var confirmCallback = function () {
alert("点击确认事件回调");
};
var cancelCallback = function () {
alert("点击取消事件回调");
};
Dialog("confirm", title, msg, confirmCallback, cancelCallback);
样式
.mw-dialog {
position: fixed;
top: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, .7);
display: flex;
place-content: center center;
.dialog {
position: fixed;
top: 50%;
left: 50%;
width: 85%;
overflow: hidden;
font-size: 16px;
background-color: #fff;
border-radius: 4px;
transform: translate3d(-50%, -50%, 0);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
transition: .3s;
}
.dialog-header {
padding-top: 24px;
font-weight: 500;
text-align: center;
}
.dialog-button {
width: 100%;
height: 50px;
line-height: 50px;
color: #323233;
text-align: center;
}
.dialog-button-confirm {
color: #1989fa;
}
.dialog-button-cancel {
border-right: .5px solid #ebedf0;
}
.dialog-message {
max-height: 400px;
white-space: pre-wrap;
text-align: center;
padding: 12px 24px 24px 24px;
font-size: 14px;
}
.dialog-footer {
border-top: .5px solid #ebedf0;
display: flex;
}
}