关于vue.js弹窗组件的知识点总结

2020-06-16 06:34:32易采站长站整理

this.instances.splice(index, 1)

// 当页面上没有弹出层了就关闭遮盖层
if (this.instances.length === 0) {
this.closeOverlay()
}
this.changeOverlayStyle()
})
},
showOverlay (color, opacity) {
let overlay = this.overlay = new Overlay({
el: document.createElement('div')
})
const dom = getDOM(overlay.$el)
dom.style.zIndex = getZIndex()
overlay.color = color
overlay.opacity = opacity
overlay.onClick = this.handlerOverlayClick.bind(this)
overlay.$appendTo(document.body)

// 禁止页面滚动
this.bodyOverflow = document.body.style.overflow
document.body.style.overflow = 'hidden'
},
closeOverlay () {
if (!this.overlay) return
document.body.style.overflow = this.bodyOverflow
let overlay = this.overlay
this.overlay = null
overlay.$remove(() => {
overlay.$destroy()
})
},
changeOverlayStyle () {
if (!this.overlay || this.instances.length === 0) return
const instance = this.instances[this.instances.length - 1] this.overlay.color = instance.overlayColor
this.overlay.opacity = instance.overlayOpacity
},
// 遮盖层点击处理,会自动调用 弹出层的 overlayClick 方法
handlerOverlayClick () {
if (this.instances.length === 0) return
const instance = this.instances[this.instances.length - 1] if (instance.overlayClick) {
instance.overlayClick()
}
}
}

window.addEventListener('keydown', function (event) {
if (event.keyCode === 27) { // ESC
if (PopupManager.instances.length > 0) {
const topInstance = PopupManager.instances[PopupManager.instances.length - 1] if (!topInstance) return
if (topInstance.escPress) {
topInstance.escPress()
}
}
}
})

export default PopupManager

最后再封装成一个 mixin


import PopupManager from './popup-manager'

export default {
props: {
show: {
type: Boolean,
default: false
},
// 是否显示遮盖层
overlay: {
type: Boolean,
default: true
},
overlayOpacity: {
type: Number,
default: 0.4
},
overlayColor: {
type: String,
default: '#000'
}
},
// 组件被挂载时会判断show的值开控制打开
attached () {
if (this.show && this.overlay) {
PopupManager.open(this)
}
},
// 组件被移除时关闭
detached () {
PopupManager.close(this)
},
watch: {
show (val) {
// 修改 show 值是调用对于的打开关闭方法
if (val && this.overlay) {
PopupManager.open(this)
} else {
PopupManager.close(this)
}
}
},
beforeDestroy () {
PopupManager.close(this)
}
}

使用