面试题答案
一键面试Teleport组件的作用
Teleport 组件能将其内部的 DOM 结构移动到 Vue 应用之外的其他 DOM 位置,而不会影响组件的逻辑和状态管理。这在处理像模态框、提示框等需要挂载到特定 DOM 节点(如 body
)的场景非常有用,避免了因组件嵌套过深导致的样式和布局问题。
关键代码片段
- 模态框组件(假设名为
Modal.vue
)
<template>
<teleport to="body">
<div class="modal-overlay" @click="closeModal">
<div class="modal-content" @click.stop>
<h2>这是一个模态框</h2>
<button @click="closeModal">关闭</button>
</div>
</div>
</teleport>
</template>
<script setup>
import { ref } from 'vue';
const isModalOpen = ref(false);
const openModal = () => {
isModalOpen.value = true;
};
const closeModal = () => {
isModalOpen.value = false;
};
</script>
<style scoped>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
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;
}
</style>
- 在父组件中使用该模态框组件
<template>
<div>
<button @click="openModal">打开模态框</button>
<Modal />
</div>
</template>
<script setup>
import Modal from './Modal.vue';
import { ref } from 'vue';
const openModal = () => {
// 这里的逻辑可以触发 Modal 组件内的 openModal 方法
};
</script>