欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue實(shí)現(xiàn)彈出框點(diǎn)擊空白頁彈框消失效果

 更新時間:2023年12月06日 10:30:17   作者:NIKKT  
這篇文章主要介紹了VUE實(shí)現(xiàn)彈出框點(diǎn)擊空白頁彈框消失,實(shí)現(xiàn)方法可以在Vue中實(shí)現(xiàn)彈出框然后通過點(diǎn)擊空白頁面來讓彈窗隱藏,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下

VUE實(shí)現(xiàn)彈出框 點(diǎn)擊空白頁彈框消失

可以在Vue中實(shí)現(xiàn)彈出框然后通過點(diǎn)擊空白頁面來讓彈窗隱藏。具體實(shí)現(xiàn)如下:

創(chuàng)建彈出框組件

在Vue中創(chuàng)建一個彈出框組件,用來呈現(xiàn)彈出框的內(nèi)容和樣式。該組件應(yīng)該接受兩個 props,一個是 show,表示彈出框是否顯示,另一個是 onClose,表示彈出框的關(guān)閉函數(shù)。

<template>
  <div v-if="show" class="modal">
    <div class="modal-body">
      <slot></slot>
      <button @click="onClose">關(guān)閉</button>
    </div>
  </div>
</template>
<script>
export default {
  props: ['show', 'onClose']
}
</script>

創(chuàng)建父組件

在父組件中使用上述彈出框組件,同時在空白區(qū)域給document綁定點(diǎn)擊事件,在點(diǎn)擊非彈出框區(qū)域時關(guān)閉彈出框。

<template>
  <div class="page">
    <button @click="showModal = true">彈出框</button>
    <modal :show="showModal" :onClose="closeModal">
      <p>這是彈出框的內(nèi)容</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 鉤子函數(shù)中給 document 綁定了一個點(diǎn)擊事件,用來監(jiān)聽頁面的點(diǎn)擊事件。在 onClickOutside 方法中,如果當(dāng)前彈出框顯示,并且點(diǎn)擊的元素不是彈出框內(nèi)的元素,則關(guān)閉彈出框。在 closeModal 方法中,我們將 showModal 設(shè)置為 false,用來隱藏彈出框組件。

添加樣式

最后,我們?yōu)閺棾隹蚝透附M件添加一些簡單的樣式。

<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實(shí)現(xiàn)彈出框點(diǎn)擊空白頁彈框消失的全部代碼實(shí)現(xiàn)。

到此這篇關(guān)于VUE實(shí)現(xiàn)彈出框 點(diǎn)擊空白頁彈框消失的文章就介紹到這了,更多相關(guān)vue彈出框內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論