以下是一个大致的实现思路:

  1. 创建一个全局弹窗组件,可以通过 Vue.prototype.$modal 进行调用。
  2. 需要在页面上添加一个蒙版,可以通过 CSS 实现,设置蒙版的样式为全屏,且 z-index 需要比弹窗的 z-index 小。同时,给蒙版添加一个点击事件,点击时调用关闭弹窗的方法。
  3. 弹窗的样式可以通过 CSS 实现,需要设置弹窗的宽度、高度、位置等属性。同时,为了实现弹窗特效,可以设置弹窗的 transform-origin 属性为中心点,再设置一个动画,使弹窗从中心点由点到面展开。
  4. 当弹窗出现时,需要禁止背景的滚动。可以通过给 body 设置 overflow:hidden 属性实现。弹窗关闭时,需要将 overflow 属性还原为原来的值。

以下是一个简单的示例代码:

<!-- modal.vue -->
<template>
  <div class="modal-mask" @click="close">
    <div class="modal-container">
      <!-- 内容插槽 -->
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    close() {
      this.$emit('close');
    }
  }
}
</script>

<style>
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-container {
  width: 400px;
  height: 300px;
  background-color: #fff;
  border-radius: 5px;
  animation: modal-show 0.5s;
  transform-origin: center center;
}

@keyframes modal-show {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}
</style>
// main.js
import Modal from './modal.vue';

Vue.prototype.$modal = function(options) {
  const ModalConstructor = Vue.extend(Modal);
  const modal = new ModalConstructor({
    el: document.createElement('div')
  });
  document.body.appendChild(modal.$el);
  // 保存原来的 overflow 属性值
  const originOverflow = document.body.style.overflow;
  // 禁止滚动
  document.body.style.overflow = 'hidden';
  // 监听关闭事件
  modal.$on('close', () => {
    modal.$el.remove();
    // 还原 overflow 属性
    document.body.style.overflow = originOverflow;
  });
  // 合并参数
  Object.assign(modal, options);
};

使用方法:

this.$modal({
  template: '<div>弹窗内容</div>'
});
``
实现一个vue全局弹窗组件背景有蒙版mask点击蒙版可以关闭弹窗位置是居中同时弹窗出现时背后的不允许滚动。弹窗特效是从中心由点到面

原文地址: https://www.cveoy.top/t/topic/fnTW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录