-teleport组件 传送组件 上代码吧
父组件
<template>
<ToRef></ToRef>
</template>
<script>
import ToRef from './components/toRef.vue'
export default {
name: 'App',
components: { ToRef },
setup() {
}
}
</script>
子组件
<template>
<h2>我是toRef组件</h2>
<span>下面是弹窗组件</span>
<dialogVue></dialogVue>
</template>
<script>
import dialogVue from './dialog.vue'
import { } from 'vue';
export default {
name: 'toRef',
components:{
dialogVue
},
setup() {
return {
};
}
}
</script>
孙组件
<template>
<h3>我是弹窗组件</h3>
<button @click="isShow = true">点击弹窗</button>
<teleport to='body' ><!-- 这里就是传送组件 to里面可以填标签如body也可以填选者器如#toRef -->
<div class="mask" v-if="isShow">
<div class="dialog-box">
<button @click="isShow = false">点击关闭</button>
</div>
</div>
</teleport>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'dialogVue',
setup() {
let isShow = ref(false);
return {
isShow
};
}
}
</script>
<style scoped>
.mask {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.dialog-box{
width: 200px;
height: 200px;
background-color: green;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
展示效果
描述:按照正常逻辑这个弹窗应该出现在toRef组件下面,但是现在出现在body下面,就是因为使用了teleport组件将其传送到了body下面
总结:teleport组件就是一种将我我们html结构传送到指定位置的一种组件