一、定义Teleport

  1. <template>
  2. <teleport to="#modal">
  3. <div id="center" v-if="isOpen">
  4. <h2>
  5. <slot>This is a modal</slot>
  6. </h2>
  7. <button @click="handleClick">关闭</button>
  8. </div>
  9. </teleport>
  10. </template>
  11. <script>
  12. import { defineComponent } from "vue";
  13. export default defineComponent({
  14. props: {
  15. isOpen: {
  16. type: Boolean,
  17. default: true,
  18. },
  19. },
  20. emits: {
  21. "close-modal": null,
  22. },
  23. setup(props, context) {
  24. const handleClick = () => {
  25. context.emit("closeModal");
  26. };
  27. return {
  28. handleClick,
  29. };
  30. },
  31. });
  32. </script>

二、父组件接收事件

  1. <template>
  2. <Modal :isOpen="isShow" @closeModal="handleModal"></Modal>
  3. <div>About</div>
  4. </template>
  5. <script setup>
  6. import { reactive, toRefs } from '@vue/reactivity'
  7. import Modal from './Children/Modal.vue'
  8. const state = reactive({
  9. isShow:true,
  10. handleModal(){
  11. state.isShow = false
  12. }
  13. })
  14. const {isShow,handleModal} = toRefs(state);
  15. </script>