vue3—可复用公共模态框

在我们日常开发中,前端开发中经常遇到这样的问题,无论是为了增加客户交互体验,还是业务需要,需要各种各样的模态框,这就需要我们封装一个公共的,兼容性很强的模态框公共组件,这里采用最新的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关闭弹框。

今天分享到这里,感谢大家,我是猿-阿焱!

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿-阿焱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值