<template>
<div>
<!-- 使用 Teleport 组件将 modal 移动到 body 根元素下 -->
<button @click="openModal">Open Modal</button>
<Teleport to="body">
<div v-if="isModalOpen" class="modal">
<div class="modal-content">
<span class="close" @click="closeModal">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</Teleport>
</div>
</template>
<script>
export default {
data() {
return {
isModalOpen: false,
};
},
methods: {
openModal() {
this.isModalOpen = true;
},
closeModal() {
this.isModalOpen = false;
},
},
};
</script>
<style>
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
position: relative;
}
.close {
position: absolute;
top: 10px;
right: 15px;
font-size: 22px;
cursor: pointer;
}
</style>
<Teleport>
是 Vue 3 提供的一个内置组件,用于将子组件的内容移动到 DOM 中的其他位置。在这个例子中,我们将模态框(modal)的内容移动到了 <body>
元素下,而不是保留在当前组件的 DOM 结构中。上一篇:vue3动态路由
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站