<template>
  <div class='dialog-wrapper' ref='dialogWrapper' @click='closeDialog'>
    <div class='dialog' ref='dialog' @click.stop>
      <div class='dialog-header'>
        <span>{{ title }}</span>
        <span class='dialog-close' @click='closeDialog'>x</span>
      </div>
      <div class='dialog-content'>
        <slot></slot>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'Dialog',
    props: {
      title: {
        type: String,
        default: 'Dialog',
      },
    },
    data() {
      return {
        isFullScreen: false,
      };
    },
    methods: {
      closeDialog() {
        this.$emit('close');
      },
      toggleFullScreen() {
        this.isFullScreen = !this.isFullScreen;
        if (this.isFullScreen) {
          this.$refs.dialog.classList.add('full-screen');
        } else {
          this.$refs.dialog.classList.remove('full-screen');
        }
      },
    },
  };
</script>
<style scoped>
.dialog-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.dialog {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.2);
  padding: 20px;
  width: 500px;
  max-height: 80vh;
  overflow: auto;
  transition: all 0.3s ease-in-out;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.dialog-close {
  cursor: pointer;
}

.full-screen {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100vw;
  height: 100vh;
  max-height: none;
  border-radius: 0;
}
</style>
<p>该代码通过一个名为 Dialog 的 Vue 组件实现了弹框放大缩小功能,并保证弹框不会超出页面。下面是代码的详细解释:</p>
<ul>
<li><strong>template:</strong> 定义弹框的结构,包含一个 <code>dialog-wrapper</code> 元素用于定位弹框,以及一个 <code>dialog</code> 元素用于显示弹框内容。</li>
<li><strong>script:</strong> 包含组件的逻辑代码,包括 props、data、methods 等。</li>
<li><strong>props:</strong> 用于接收外部传入的弹框标题。</li>
<li><strong>data:</strong> 存储弹框状态,<code>isFullScreen</code> 用于标识弹框是否处于全屏状态。</li>
<li><strong>methods:</strong> 定义组件的方法,<code>closeDialog</code> 用于关闭弹框,<code>toggleFullScreen</code> 用于切换弹框的全屏状态。</li>
<li><strong>style:</strong> 定义弹框的样式,包含 <code>dialog-wrapper</code>、<code>dialog</code> 和 <code>full-screen</code> 等样式。</li>
</ul>
<p><strong>关键点:</strong></p>
<ul>
<li>使用 <code>position: fixed</code> 和 <code>transform: translate(-50%, -50%)</code> 来实现弹框居中。</li>
<li>使用 <code>max-height: 80vh</code> 来限制弹框的高度,防止内容超出页面。</li>
<li>使用 <code>overflow: auto</code> 来实现弹框内容超出时的滚动条。</li>
<li>使用 <code>@click.stop</code> 来阻止事件冒泡,避免点击弹框内容时关闭弹框。</li>
<li>在 <code>toggleFullScreen</code> 方法中,通过添加或移除 <code>full-screen</code> 类来实现弹框的样式变化。</li>
</ul>
<p>该代码实现了弹框的基本功能,可以根据实际需求进行修改和扩展。例如,可以添加更多样式,或添加其他功能,例如拖拽、动画等。</p>
Vue 弹框放大缩小不超出页面:完整代码示例和解释

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

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