定义:可以将组件的DOM元素直接传送到某一位置进行展示。
- 使用场景:像 modals,toast 等这样的元素,很多情况下,我们将它完全的和我们的 Vue 应用的 DOM 完全剥离,管理起来反而会方便容易很多
1、未使用teleport的时候
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<style>
.area {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background: black;
}
.mask {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: green;
opacity: 0.5;
}
</style>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root">
<div class="area">
<button @click="handleClick">按钮</button>
<div class="mask" v-show="show"></div>
</div>
</div>
</body>
<script>
//自定义指令
const app = Vue.createApp({
data() {
return {
show: false
}
},
methods: {
handleClick() {
this.show = !this.show
}
},
});
const vm = app.mount('#root');
</script>
</html>
效果:蒙层在div内部
image.png
2、使用teleport的时候
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<style>
.area {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background: black;
}
.mask {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: green;
opacity: 0.5;
}
</style>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root">
<div class="area">
<button @click="handleClick">按钮</button>
<teleport to='#mask'>
<div class="mask" v-show="show"></div>
</teleport>
</div>
</div>
<div id="mask"></div>
</body>
<script>
//自定义指令
const app = Vue.createApp({
data() {
return {
show: false
}
},
methods: {
handleClick() {
this.show = !this.show
}
},
});
const vm = app.mount('#root');
</script>
</html>
效果:
image.png
网友评论