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>
阅读 3.9k
2 个回答

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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏