面试题答案
一键面试- 使用Teleport将组件渲染到
body
下: Teleport 组件可以将其包裹的内容渲染到指定的 DOM 元素下。
<template>
<div>
<button @click="showPopup = true">打开弹窗</button>
<teleport to="body">
<popup v-if="showPopup" @close="showPopup = false"></popup>
</teleport>
</div>
</template>
<script setup>
import Popup from './Popup.vue'
import { ref } from 'vue'
const showPopup = ref(false)
</script>
- 在弹窗组件中使用Fragment处理多个根节点:
在 Vue 3 中,组件可以有多个根节点,无需额外处理。如果在 Vue 2 中,可使用
Fragment
模拟多个根节点。假设Popup.vue
如下:
<template>
<Fragment>
<div class="popup-content">
<h2>弹窗标题</h2>
<p>弹窗内容</p>
</div>
<button @click="$emit('close')">关闭</button>
</Fragment>
</template>
<script>
// 在 Vue 2 中引入 Fragment 相关处理(这里只是示意,实际引入方式按项目配置)
import { Fragment } from 'vue-fragment'
export default {
components: { Fragment }
}
</script>
<style scoped>
.popup-content {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
</style>
在上述代码中,通过 Teleport
将弹窗组件渲染到 body
下,弹窗组件内部使用 Fragment
(Vue 2 中需引入,Vue 3 可直接多根节点)来处理多个根节点的情况。