vue组件怎么添加到body里?

点击按钮的时候,把子节点append到body里,但是默认情况Children组件也渲染了,怎么能默认不渲染,点击的时候append到body里呢

<template>

<button @click="click">按钮</button>

<Children v-model="msg" ref="childrenRef"></Children>

</template>

<script setup lang="ts">

import { ref } from 'vue'

import Children from "./components/HelloWorld.vue"

const msg = ref('')

const childrenRef = ref()

const click = () => {

const bodyEl = document.querySelector('body')

bodyEl?.append(childrenRef.value.$el)

}

</script>


回答:

vue3有个标签叫 teleport,

<button @click="click">按钮</button>

<Teleport to="body">

<Children v-if="show" v-model="msg"></Children>

</Teleport>

<script setup lang="ts">

import { ref } from 'vue'

import Children from "./components/HelloWorld.vue"

const msg = ref('')

const show = ref(false)

const click = () => {

show.value = true

}

</script>


回答:

Children组件加个v-show

<template>

<button @click="click">按钮</button>

<Children v-show="show" v-model="msg" ref="childrenRef"></Children>

</template>

<script setup lang="ts">

import { ref } from 'vue'

import Children from "./components/HelloWorld.vue"

const msg = ref('')

const childrenRef = ref()

const show = ref(false)

const click = () => {

const bodyEl = document.querySelector('body')

show.value = true

bodyEl?.append(childrenRef.value.$el)

}

</script>

以上是 vue组件怎么添加到body里? 的全部内容, 来源链接: utcz.com/p/934038.html

回到顶部