手写Vue弹窗Modal的实现代码

2020-06-13 10:32:05易采站长站整理

我们vue项目中应该也遇到过这种情况,弹出一个对话框或是选择框?不但要求用方法弹出,并且能接收到对话框交互所返回的结果。

这里就不详细的分析了直接上代码说(之前的代码,用render来写的组件,懒得改了,直接拿来用…),先创建一个对话框组件—Confirm.vue


<script>
let __this = null
export default {
name: 'Confirm',
data() {
return {
config: {
msg: '',
ifBtn: '',
top: null
}
}
},
created() {
__this = this
},
methods: {
createBox(h) {
let config = {}
config.attrs = {
id: '__confirm'
}
let children = [] children.push(this.createContainer(h))
children.push(this.createBg(h))
return h('div', config, children)
},
createBg(h) {
return h('div', {
class: 'bg',
on: {
click: __this.$cancel
}
})
},
createContainer(h) {
let config = {}
config.class = {
'box-container': true
}
if (__this.config.top) {
config.style = {
'top': __this.config.top + 'px',
'transform': 'translate(-50%, 0)'
}
}
let children = [] children.push(this.createContentBox(h))
children.push(this.createClose(h))
if (__this.config.ifBtn) {
children.push(__this.createBtnBox(h))
}
return h('div', config, children)
},
createContentBox(h) {
let config = {}
config.class = {
'content-box': true
}
return h('div', config, [__this.createContent(h)])
},
createContent(h) {
let config = {}
config.domProps = {
innerHTML: __this.config.msg
}
return h('p', config)
},
createClose(h) {
return h('i', {
class: 'eqf-no pointer close-btn',
on: {
click: __this.$cancel
}
})
},
createBtnBox(h) {
return h(
'div', {
class: {
'btn-box': true
}
}, [
__this.createBtn(h, 'btn-cancel middle mr10', '取消', __this.$cancel),
__this.createBtn(h, 'btn-primary middle mr10', '确定', __this.$confirm)
])
},
createBtn(h, styles, content, callBack) {
return h('button', {
class: styles,
on: {
click: callBack