<script setup>
const isMounted = ref(false)

const { to, clearChildren } = defineProps({
  to: {
    type: String,
    required: true,
    default: 'body',
  },
  clearChildren: {
    type: Boolean,
    default: true,
  }
})

const vm = getCurrentInstance().proxy

// 挂载时
onMounted(() => {
  isMounted.value = true
  if (clearChildren) {
    document.querySelector(to)?.childNodes.forEach(node => {
      node.style.display = 'none'
    })
  }
  document.querySelector(to)?.appendChild(vm.$el)
})

// 组件激活时
onActivated(() => {
  if (isMounted.value) return
  document.querySelector(to)?.appendChild(vm.$el)
})

// 路由切换移除
onDeactivated(() => {
  isMounted.value = false
  vm?.$el?.parentNode.removeChild(vm.$el)
})

// 销毁时移除
onUnmounted (() => {
  isMounted.value = false
  vm?.$el?.parentNode?.removeChild(vm.$el)
  document.querySelector(to)?.childNodes.forEach(node => {
    node.style.display = 'block'
  })
})

</script>

<template>
  <div class='teleport'>
    <slot></slot>
  </div>
</template>
