Vue移动 HTML 元素到指定位置 teleport 标签

teleport 标签:用于将组件中的 HTML 元素移动到任意的位置。

使用 teleport 标签移动 HTML 元素:

html 复制代码
<!-- 将 teleport 中的内容移动到 body 标签中  -->
<teleport to="body">
    <div>
        <h3>我是第三层组件的标题</h3>
        <p>我是第三层组件的内容</p>
        <p>我是第三层组件的内容</p>
        <p>我是第三层组件的内容</p>
    </div>
</teleport>

注:teleport 标签也可以通过 id 名移动,例如:`<teleport to="#box">`

使用 teleport 标签制作全局弹窗:

第一层组件:

html 复制代码
<template>
  <div class="one">
    <h3>我是One组件(第一层)</h3>
    <hr />
    <Two></Two>
  </div>
</template>

<script>
import Two from '../components/Two';
export default {
  name: "One",
  components: { Two }
}
</script>

第二层组件:

html 复制代码
<template>
    <div class="two">
        <h3>我是Two组件(第二层)</h3>
        <hr />
        <Three></Three>
    </div>
</template>

<script>
import Three from "../components/Three.vue"
export default {
    name: "Two",
    components: { Three }
}
</script>

第三层组件(弹窗组件):使用 teleport 标签将弹窗内容移动到 body 标签中。

javascript 复制代码
<template>
    <button @click="isShow = true">显示弹窗</button>
    <teleport to="body">
        <div class="mask" v-if="isShow">
            <div class="dialog">
                <h3>我是弹窗的标题</h3>
                <p>我是弹窗的内容</p>
                <p>我是弹窗的内容</p>
                <p>我是弹窗的内容</p>
                <button @click="isShow = false">关闭弹窗</button>
            </div>
        </div>
    </teleport>
</template>

<script>
import { ref } from 'vue'
export default {
    name: "Three",
    setup() {
        let isShow = ref(false);
        return { isShow }
    }
}
</script>

<style scoped>
.mask {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
}

.dialog {
    width: 300px;
    padding: 20px;
    background-color: aqua;
    text-align: center;
}
</style>

最终效果:

原创作者:吴小糖

创作时间:2023.11.21

相关推荐
六月June June4 小时前
自定义调色盘组件
前端·javascript·调色盘
SY_FC5 小时前
实现一个父组件引入了子组件,跳转到其他页面,其他页面返回回来重新加载子组件函数
java·前端·javascript
糟糕好吃5 小时前
我让 AI 操作网页之后,开始不想点按钮了
前端·javascript·后端
陈天伟教授5 小时前
人工智能应用- 天文学家的助手:08. 星系定位与分类
前端·javascript·数据库·人工智能·机器学习
VaJoy5 小时前
给到夯!前端工具链新标杆 Vite Plus 初探
前端·vite
小彭努力中7 小时前
191.Vue3 + OpenLayers 实战:可控化版权信息(Attribution)详解与完整示例
前端·javascript·vue.js·#地图开发·#cesium
奇舞精选7 小时前
用去年 github 最火的 n8n 快速实现自动化推送工具
前端·agent
奇舞精选7 小时前
实践:如何为智能体推理引入外部决策步骤
前端·agent
无限大67 小时前
AI实战02:一个万能提示词模板,搞定90%的文案/设计/分析需求
前端·后端
朝阳5817 小时前
控制 Nuxt 页面的渲染模式:客户端 vs 服务端渲染
前端·javascript