VUE3 之 Teleport - 这个系列的教程通俗易懂,适合新手
阅读原文时间:2022年05月11日阅读:1

1. 概述

老话说的好:宰相肚里能撑船,但凡成功的人,都有一种博大的胸怀。

言归正传,今天我们来聊聊 VUE 中 Teleport 的使用。

2. Teleport

2.1 遮罩效果的实现

<style>  
   .area {  
        position: absolute;  
        left: 50%;  
        top: 50%;  
        transform: translate(-50%, -50%);  
        width: 200px;  
        height: 300px;  
        background: rgb(16, 209, 48);

   }  
   .mask {  
       position: absolute;  
       left: 0;  
       right: 0;  
       top: 0;  
       bottom: 0;  
       background: #000;  
       opacity: 50%;  
   }  
</style>

const app = Vue.createApp({  
   data() {  
        return {  
            show : false  
        }  
   },  
   methods: {  
        handleClick(){  
            this.show = !this.show;  
        }  
   },  
   template:\`  
       <div class="area">  
           <button @click="handleClick">按钮</button>  
            <div class="mask" v-show="show"></div>  
       </div>  
   \`  

});

const vm = app.mount("#myDiv");

这个例子,我们实现了一个简单的遮罩效果,但这个遮罩效果并没有遮罩整个背景,只是遮罩了 area 这个div。

2.2 Teleport 的使用

const app = Vue.createApp({  
   data() {  
        return {  
            show : false  
        }  
   },  
   methods: {  
        handleClick(){  
            this.show = !this.show;  
        }  
   },  
   template:\`  
       <div class="area">  
           <button @click="handleClick">按钮</button>  
           <teleport to="body" >  
                <div class="mask" v-show="show"></div>  
           </teleport>  
       </div>  
   \`  

});

这个例子中,我们改进了一下,使用  将遮罩的 div 转移到了 body 元素下,因此遮罩范围扩大到了整个 body 的区域。

2.3 Teleport 通过 元素id 转移元素到指定元素下

const app = Vue.createApp({
data() {
return {
show : false
}
},
methods: {
handleClick(){
this.show = !this.show;
}
},
template:`




`
});

这个例子中,通过  的写法,将 遮罩div 转移到了 id 是 maskDiv 的元素下。

3. 综述

今天聊了一下 VUE 中 Teleport 的使用,希望可以对大家的工作有所帮助,下一节我们继续讲 Vue 中的高级语法,敬请期待

欢迎帮忙点赞、评论、转发、加关注 :)

关注追风人聊Java,这里干货满满,都是实战类技术文章,通俗易懂,轻松上手。

4. 个人公众号

追风人聊Java,欢迎大家关注

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章