言归正传,今天我们来聊聊 VUE 中 Teleport 的使用。
Teleport.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";
这个例子,我们实现了一个简单的遮罩效果,但这个遮罩效果并没有遮罩整个背景,只是遮罩了 area 这个div。
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> ` };
这个例子中,我们改进了一下,使用 <teleport to="body" > 将遮罩的 div 转移到了 body 元素下,因此遮罩范围扩大到了整个 body 的区域。
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 的元素下。
综述
今天聊了一下 VUE 中 Teleport 的使用,希望可以对大家的工作有所帮助。
关注追风人聊Java,这里干货满满,都是实战类技术文章,通俗易懂,轻松上手。
个人公众号
追风人聊Java,欢迎大家关注