在我们日常开发中,前端开发中经常遇到这样的问题,无论是为了增加客户交互体验,还是业务需要,需要各种各样的模态框,这就需要我们封装一个公共的,兼容性很强的模态框公共组件,这里采用最新的vue3来实现一个可用作公共组件的带过渡动效的模态框。
首先我们实现调用它的组件,也就是父组件:
// app.vue
<script setup>
import { ref } from 'vue'
import Modal from './ModalComponent.vue'
const showModal = ref(false)
const phone = ref('apple')
</script>
<template>
<button id="show-modal" @click="showModal = true">
展示弹框
</button>
<Teleport to="body">
<modal :showM="showModal" @closeModal="showModal = false">
// 这里可定制化的编写业务所需要的模态框头部
<template #header>
<h1>选择你的手机</h1>
</template>
// 这里可定制化的编写业务所需要的模态框内容
<template #body>
<input type="radio" value="apple" v-model="phone">苹果
<input type="radio" value="andrio" v-model="phone">安卓
</template>
</modal>
</Teleport>
</template>
其次我们来实现公共的模态框组件:
// Modalcomponent.vue
<script setup>
const props = defineProps({
showM: Boolean
})
</script>
<template>
<Transition name="modal">
<div v-if="showM" class="modal-mask">
<div class="modal-container">
<div class="modal-header">
<slot name="header">这是默认的头部</slot>
</div>
<div class="modal-body">
<slot name="body">这是默认的模态框body</slot>
</div>
<div class="modal-footer">
<slot name="footer">
//这是默认的模态框footer
<button
class="modal-default-button" @click="$emit('closeModal')"
>OK</button>
</slot>
</div>
</div>
</div>
</Transition>
</template>
<style>
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
transition: opacity 0.3s ease;
}
.modal-container {
width: 300px;
margin: auto;
padding: 20px 30px;
background-color: #fff;
border-radius: 2px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
transition: all 0.3s ease;
}
.modal-header h3 {
margin-top: 0;
color: #42b983;
}
.modal-body {
margin: 20px 0;
}
.modal-default-button {
float: right;
}
/*
* 对于 transition="modal" 的元素来说
* 当通过 Vue.js 切换它们的可见性时
* 以下样式会被自动应用。
*
* 你可以简单地通过编辑这些样式
* 来体验该模态框的过渡效果。
*/
.modal-enter-from {
opacity: 0;
}
.modal-leave-to {
opacity: 0;
}
.modal-enter-from .modal-container,
.modal-leave-to .modal-container {
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.5s ease
}
</style>
在公共子组件中,用插槽slot的形式实现内容的可定制化,以满足实际业务的需求。
以上demo实现的效果如下图:
当点击展示弹框按钮时,弹出弹框,点击ok关闭弹框。
今天分享到这里,感谢大家,我是猿-阿焱!