0
点赞
收藏
分享

微信扫一扫

VUE3 之 Teleport - 这个系列的教程通俗易懂,适合自学


目录

​​1. 概述​​

​​2. Teleport​​

​​3. 综述​​

​​4. 个人公众号​​

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>
<body>
<div id="myDiv"></div>
</body>
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");

VUE3 之 Teleport - 这个系列的教程通俗易懂,适合自学_微信

 这个例子,我们实现了一个简单的遮罩效果,但这个遮罩效果并没有遮罩整个背景,只是遮罩了 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>
`
});

VUE3 之 Teleport - 这个系列的教程通俗易懂,适合自学_微信_02

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

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

<body>
<div id="myDiv"></div>
<div id="maskDiv"></div>
</body>


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

这个例子中,通过 <teleport to="#maskDiv" > 的写法,将 遮罩div 转移到了 id 是 maskDiv 的元素下。 

3. 综述

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

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

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

4. 个人公众号

微信搜索公众号:追风人聊Java,欢迎大家关注


举报

相关推荐

0 条评论