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

相关推荐
冷冷的菜哥6 分钟前
react多文件分片上传——支持拖拽与进度展示
前端·react.js·typescript·多文件上传·分片上传
玄魂20 分钟前
VChart 官网上线 智能助手与分享功能
前端·llm·数据可视化
Lucky GGBond36 分钟前
Vue + Spring Boot 实现 Excel 导出实例
vue.js·spring boot·excel
wyzqhhhh1 小时前
插槽vue/react
javascript·vue.js·react.js
许___1 小时前
Vue使用原生方式把视频当作背景
前端·javascript·vue.js
萌萌哒草头将军1 小时前
尤雨溪强烈推荐的这个库你一定要知道 ⚡️⚡️⚡️
前端·vue.js·vite
2401_878454531 小时前
Vue 核心特性详解:计算属性、监听属性与事件交互实战指南
前端·vue.js·交互
1024小神2 小时前
uniapp+vue3+vite+ts+xr-frame实现ar+vr渲染踩坑记
前端
测试界清流2 小时前
基于pytest的接口测试
前端·servlet
知识分享小能手2 小时前
微信小程序入门学习教程,从入门到精通,自定义组件与第三方 UI 组件库(以 Vant Weapp 为例) (16)
前端·学习·ui·微信小程序·小程序·vue·编程