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

2020-06-16 06:34:32易采站长站整理
mixins 
机制,将这些弹出层的公共逻辑封装层一个 mixin ,每个弹出框组件直接引用就好。

vue-popup-mixin

明确了上述所有的问题,开始开发 mixin, 首先需要一个

overlay 
(遮盖层组件) ;


<template>
<div class="overlay" @click="handlerClick" @touchmove="prevent" :style="style" transition="overlay-fade"></div>
</template>
<script>
export default {
props: {
onClick: {
type: Function
},
opacity: {
type: Number,
default: 0.4
},
color: {
type: String,
default: '#000'
}
},
computed: {
style () {
return {
'opacity': this.opacity,
'background-color': this.color
}
}
},
methods: {
prevent (event) {
event.preventDefault()
event.stopPropagation()
},
handlerClick () {
if (this.onClick) {
this.onClick()
}
}
}
}
</script>
<style lang="less">
.overlay {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: #000;
opacity: .4;
z-index: 1000;
}

.overlay-fade-transition {
transition: all .3s linear;
&.overlay-fade-enter,
&.overlay-fade-leave {
opacity: 0 !important;
}
}
</style>

然后 需要一个 js 来管理

overlay 
的显示和隐藏。


import Vue from 'vue'
import overlayOpt from '../overlay' // 引入 overlay 组件
const Overlay = Vue.extend(overlayOpt)

const getDOM = function (dom) {
if (dom.nodeType === 3) {
dom = dom.nextElementSibling || dom.nextSibling
getDOM(dom)
}
return dom
}

// z-index 控制
const zIndex = 20141223

const getZIndex = function () {
return zIndex++
}
// 管理
const PopupManager = {
instances: [], // 用来储存所有的弹出层实例
overlay: false,
// 弹窗框打开时 调用此方法
open (instance) {
if (!instance || this.instances.indexOf(instance) !== -1) return

// 当没有遮盖层时,显示遮盖层
if (this.instances.length === 0) {
this.showOverlay(instance.overlayColor, instance.overlayOpacity)
}
this.instances.push(instance) // 储存打开的弹出框组件
this.changeOverlayStyle() // 控制不同弹出层 透明度和颜色

// 给弹出层加上z-index
const dom = getDOM(instance.$el)
dom.style.zIndex = getZIndex()
},
// 弹出框关闭方法
close (instance) {
let index = this.instances.indexOf(instance)
if (index === -1) return

Vue.nextTick(() => {