如何使用vue slot创建一个模态框的实例代码

2020-06-16 06:57:54易采站长站整理

【1】遮罩层:承载内容,管理样式布局。

【2】内容层:控制遮罩层的显示与否。

遮罩层和内容区之间应该解耦。遮罩层和内容区之间应该解耦。遮罩层和内容区之间应该解耦。

遮罩层不依赖于内容区,内容是放置在遮罩层里的,至于内容区里的内容是什么,遮罩层完全不用在意。因此可以在遮罩层里采用插槽。

遮罩层的实现


<div class="common-mask" v-if="visible">
<slot name="head"></slot>
<slot name="body"></slot>
<slot name="foot"></slot>
</div>


<style scoped lang='scss'>
.common-mask {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba($color: #000000, $alpha: 0.75);
display: flex;
justify-content: center;
align-content: center;
z-index: 4;
}
</style>

内容层的实现


<Vue-Modal :visible="visible">
<div slot="head">head</div>
<div slot="body">body</div>
<div slot="foot">
<button class="common-btn" @click="close">Close</button>
</div>
</Vue-Modal>

PS:vue组件模态框实现方式

// 组件代码


<template>
<div>
<div class="dialog-modal"> <!-- 根元素,z-index 需要高于父容器其他元素 -->
<div class="dialog-wrapper" @click="onClose" v-show="isShow"></div> <!-- 加载一个具有透明度的背景,使根元素透明,子元素会继承该透明度 -->
<transition name="drop">
<div class="dialog-container" v-show="isShow"> <!-- 模态框容器,z-index 需要高于背景 -->
<span class="close-btn" @click="onClose">x</span>
<slot>
<p>hello</p>
</slot>
</div>
</transition>
</div>
</div>
</template>
<script>
export default {
props: {
isShow:{
type: Boolean,
default: false
}
},
methods: {
onClose(){
this.$emit('on-close');
}
}
}
</script>
<style>
.drop-enter-active {
transition: all .5s;
}
.drop-leave-active {
transition: all .3s;
}
.drop-enter {
transform: translateY(-500px);
}
.drop-leave-active {
transform: translateY(-500px);
}

.dialog-modal{
position: absolute;
z-index: 5;
}
.dialog-wrapper
{
position: fixed;