vue3.js
<style> .alert{ width: 100vw; height: 100vh; background-color: #000b; position: absolute; top: 0; left: 0; display: flex; justify-content: center; align-items: center; z-index: 10000; } .alert h1{ background-color: white; width: 50vw; height: 50vh; line-height: 100px; } #myApp{ position: relative; z-index: 1; } #mydom{ position: relative; z-index: 2; } /* 此时, 上边设置的样式结果: alert自定义弹窗无法覆盖mydom */ </style><body> <script src='./vue3.js'></script> <div id='myApp'> <button @click="count=!count">{{count}}</button> <!-- teleport 是vue3新增的一个功能, 叫传送器, 作用: 把组件模板内的元素渲染到组件模板外部 特点: 传送的是dom元素不是数据, 通过修改DOM元素位置实现 --> <teleport to='#outer'> <h1 v-show="count">这是一个警告框</h1> </teleport> <!-- 传送器可以把组件传送到模板外部, 但仅在外部渲染, 实际功能依然保留vue组件功能(可以调用组件API) --> <teleport to='body'> <my-alert v-show="count" @off="close"></my-alert> </teleport> </div> <h1 id="mydom"><hr><button> 这是组件模板外部的DOM结构 </button><hr></h1> <div id="outer"></div> <template id="com"> <div class="alert"> <h1 >这是一个警告框</h1> <button @click="close">关闭</button> </div> </template> <script> var myAlert = { template: "#com", emits: ['off'], setup(props, {emit}){ return { close: ()=>{ emit("off", false) } } } } var vm = { components: {myAlert}, setup() { const count = Vue.ref(false) return{ count, close: data=>{ count.value = data } } } } Vue.createApp(vm).mount('#myApp') </script></body>