准备三个组件
<template>
<div class="app">
<h1>我是App组件</h1>
<chlid></chlid>
</div>
</template>
<script>
import { provide, reactive, toRefs } from "vue";
import chlid from "@/components/child.vue";
export default {
components: {
chlid,
},
};
</script>
<style scoped>
.app {
background: pink;
padding: 20px;
}
</style>
<template>
<div class="child">
<h2>我是child组件</h2>
<son></son>
</div>
</template>
<script>
import { reactive, toRefs } from "vue";
import son from "@/components/son.vue";
export default {
name: "chlid",
components: {
son,
},
};
</script>
<style scoped>
.child {
background: red;
padding: 20px;
}
</style>
<template>
<div class="son">
<h3>我是孙组件</h3>
</div>
</template>
<script>
import { reactive, toRefs } from "vue";
export default {
name: "son",
};
</script>
<style scoped>
.son {
background: yellow;
padding: 20px;
}
</style>
实现一个需求
写一个简单的dialog组件
<template>
<div>
<button @click="isShow = true">弹窗</button>
<div class="dialog" v-if="isShow">
<h3>弹窗</h3>
<h4>内容</h4>
<h4>内容</h4>
<h4>内容</h4>
<button @click="isShow = false">关闭弹窗</button>
</div>
</div>
</template>
<script>
import { ref } from "vue";
export default {
name: "dialog",
setup() {
let isShow = ref(false);
return {
isShow,
};
},
};
</script>
<style>
.dialog {
width: 300px;
height: 300px;
background: blue;
}
</style>
使用时会发现,父组件被撑开了
可以看到,弹窗在son里面
应用以下teleport
<div>
<button @click="isShow = true">弹窗</button>
<teleport to="body">
<div class="dialog" v-if="isShow">
<h3>弹窗</h3>
<h4>内容</h4>
<h4>内容</h4>
<h4>内容</h4>
<button @click="isShow = false">关闭弹窗</button>
</div>
</teleport>
</div>
</template>
结构也没有被撑开