Vue.js 3 modal with teleport
by ChangJoo Park
HTML
<script src="https://unpkg.com/vue@3"></script>
<div id="app">
<modal-button>
</modal-button>
</div>
CSS
.modal {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
background-color: rgba(0,0,0,.5);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.modal div {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: white;
width: 300px;
height: 300px;
padding: 5px;
}
JavaScript
const { setup, createApp, defineComponent, ref } = Vue
const app = createApp({})
app.component('ModalButton', {
template: `
<button @click="modalOpen = true">
Open full screen modal!
</button>
<teleport to="body">
<div v-if="modalOpen" class="modal">
<div>
I'm a modal!
<button @click="modalOpen = false">
Close
</button>
</div>
</div>
</teleport>
`,
setup() {
const modalOpen = ref(false);
return {
modalOpen
}
},
})
app.mount('#app')