天天看点

vue组件移动在DOM节点中的位置

Vue2

mounted() {
	this.$nextTick(() => {
		const body = document.querySelector('body')
		body.append(body)
	})
}
           

Vue3方式:使用Teleport组件

<template>
	<button @click="open = true">
        Open
    </button>

    <teleport to="body">
      <div v-if="open">
        <div>
          Modal Content
          <button @click="open = false">
            Close
          </button>
        </div>
      </div>
    </teleport>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
	name: 'TeleportDemo',
	setup() {
		const open = ref(false)
		
		return {
			open
		}
	}
})
</script>