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