VUE实现弹出框 点击空白页弹框消失

VUE实现弹出框 点击空白页弹框消失

可以在Vue中实现弹出框然后通过点击空白页面来让弹窗隐藏。具体实现如下:

  1. 创建弹出框组件

在Vue中创建一个弹出框组件,用来呈现弹出框的内容和样式。该组件应该接受两个 props,一个是 show,表示弹出框是否显示,另一个是 onClose,表示弹出框的关闭函数。

<template>
  <div v-if="show" class="modal">
    <div class="modal-body">
      <slot></slot>
      <button @click="onClose">关闭</button>
    </div>
  </div>
</template>

<script>
export default {
  props: ['show', 'onClose']
}
</script>
  1. 创建父组件

在父组件中使用上述弹出框组件,同时在空白区域给document绑定点击事件,在点击非弹出框区域时关闭弹出框。

<template>
  <div class="page">
    <button @click="showModal = true">弹出框</button>
    <modal :show="showModal" :onClose="closeModal">
      <p>这是弹出框的内容</p>
    </modal>
  </div>
</template>

<script>
import Modal from './Modal.vue'

export default {
  components: {
    Modal
  },

  data() {
    return {
      showModal: false
    }
  },

  created() {
    document.addEventListener('click', this.onClickOutside);
  },

  beforeDestroy() {
    document.removeEventListener('click', this.onClickOutside);
  },

  methods: {
    onClickOutside(event) {
      if (this.showModal && !this.$el.contains(event.target)) {
        this.closeModal();
      }
    },

    closeModal() {
      this.showModal = false
    }
  }
}
</script>

在父组件中,我们使用 v-if 指令来判断弹出框是否显示。同时,我们在 created 钩子函数中给 document 绑定了一个点击事件,用来监听页面的点击事件。在 onClickOutside 方法中,如果当前弹出框显示,并且点击的元素不是弹出框内的元素,则关闭弹出框。在 closeModal 方法中,我们将 showModal 设置为 false,用来隐藏弹出框组件。

  1. 添加样式

最后,我们为弹出框和父组件添加一些简单的样式。

<style>
.page {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1000;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-body {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  padding: 20px;
}
</style>

以上是Vue实现弹出框点击空白页弹框消失的全部代码实现。

猜你喜欢

转载自blog.csdn.net/NIKKT/article/details/129954872
今日推荐