MST

星途 面试题库

面试题:Vue Teleport与Portal技术在复杂布局中的应用

在一个具有多层嵌套组件且布局复杂的Vue应用中,有一个全局提示组件,要求使用Teleport和Portal技术,无论提示组件在哪个层级,都能准确显示在页面顶部特定的容器内,并且不影响其与原组件数据的双向绑定,请详细阐述实现思路并给出核心代码。
38.8万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建全局提示组件:在Vue应用中,创建一个用于显示提示信息的组件,该组件包含需要双向绑定的数据。
  2. 使用Teleport组件:Teleport提供了一种将组件的一部分“瞬移”到DOM中其他位置的能力。利用Teleport将提示组件移动到页面顶部特定的容器内。
  3. 保持数据双向绑定:通过props和$emit来实现数据的双向绑定,确保提示组件在新的位置依然能和原组件保持数据同步。

核心代码

  1. 创建提示组件 GlobalTip.vue
<template>
  <teleport to="#top-container">
    <div class="global-tip">
      {{ tipMessage }}
      <input v-model="inputValue" />
    </div>
  </teleport>
</template>

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

const props = defineProps({
  tipMessage: String,
  inputValue: String
});

const emit = defineEmits(['update:inputValue']);

const handleInputChange = (value) => {
  emit('update:inputValue', value);
};
</script>

<style scoped>
.global-tip {
  position: fixed;
  top: 0;
  left: 0;
  background-color: lightblue;
  padding: 10px;
}
</style>
  1. 在父组件中使用 GlobalTip.vue
<template>
  <div>
    <GlobalTip 
      :tipMessage="parentTipMessage" 
      :inputValue="parentInputValue" 
      @update:inputValue="updateParentInputValue"
    />
    <p>Parent input value: {{ parentInputValue }}</p>
  </div>
</template>

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

const parentTipMessage = ref('This is a global tip');
const parentInputValue = ref('Initial value');

const updateParentInputValue = (value) => {
  parentInputValue.value = value;
};
</script>
  1. index.html 中创建目标容器
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue Teleport Example</title>
</head>
<body>
  <div id="top-container"></div>
  <div id="app"></div>
  <script src="/dist/js/app.js"></script>
</body>
</html>