MST
星途 面试题库

面试题:Vue Teleport 与组件通信结合优化

假设你正在开发一个 Vue 应用,有一个模态框组件使用了 Vue Teleport 移动到 body 下。现在要实现模态框与父组件之间的双向数据绑定通信,在不影响 Teleport 功能的前提下,你会如何优化代码来实现高效通信?请给出详细代码思路及关键代码片段。
25.9万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 代码思路
    • 使用 Vue 的响应式数据和事件系统来实现双向数据绑定。
    • 在父组件中定义数据,并通过 props 将数据传递给模态框组件。
    • 模态框组件通过 $emit 触发事件,将数据变化通知给父组件,父组件监听事件并更新数据。由于使用了 Teleport 移动到 body 下,组件间的层级关系虽有变化,但 Vue 的事件系统依然有效。
  2. 关键代码片段
    • 父组件(假设为 Parent.vue
<template>
  <div>
    <button @click="showModal = true">打开模态框</button>
    <Modal :show="showModal" @update:show="showModal = $event" />
  </div>
</template>

<script setup>
import Modal from './Modal.vue';
import { ref } from 'vue';

const showModal = ref(false);
</script>
  • 模态框组件(Modal.vue
<template>
  <teleport to="body">
    <div v-if="show" class="modal">
      <div class="modal-content">
        <button @click="closeModal">关闭</button>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';

const props = defineProps(['show']);
const emits = defineEmits(['update:show']);

const closeModal = () => {
  emits('update:show', false);
};
</script>

<style scoped>
.modal {
  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>