Vue實(shí)現(xiàn)彈出框點(diǎn)擊空白頁彈框消失效果
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)文章
vue項(xiàng)目配置sass及引入外部scss文件方式
這篇文章主要介紹了vue項(xiàng)目配置sass及引入外部scss文件方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04vue前端測試開發(fā)watch監(jiān)聽data的數(shù)據(jù)變化
這篇文章主要為大家介紹了vue測試開發(fā)watch監(jiān)聽data的數(shù)據(jù)變化,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05在vue中路由使用this.$router.go(-1)返回兩次問題
這篇文章主要介紹了在vue中路由使用this.$router.go(-1)返回兩次問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12在vue項(xiàng)目中promise解決回調(diào)地獄和并發(fā)請求的問題
這篇文章主要介紹了在vue項(xiàng)目中promise解決回調(diào)地獄和并發(fā)請求的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Vue使用自定義指令實(shí)現(xiàn)頁面底部加水印
本文主要實(shí)現(xiàn)給項(xiàng)目的整個背景加上自定義水印,可以改變水印的文案和字體顏色等,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06