简体   繁体   中英

Vue add content inside #document-fragment

I'm using vue3 with nuxt3 and want to add a template tag with content inside the generated #document-fragment . The resulting HTML should look like this:

<body>
  <template id="some-id">
    #document-fragment
      <div>
        ...
      </div>
  </template>
</body>

when I use plain html, that works great. With vue3 the elements are not inside the #document-fragment but below it like this:

<body>
  <template id="some-id">
    #document-fragment
    <div>
      ...
    </div>
  </template>
</body>

My vue3 code looks like this (similar to the html code):

<template>
  <v-app>
    <template id="some-id">
      <div></div>
    </template>
  </v-app>
</template>

is there any way to put the content inside the #document-fragment element?

I solved it by using a ref on the template tag and then the render -function.

<template id="some-id" ref="someRef">
</template>
const someRef: Ref<HTMLTemplateElement | undefined> = ref()
onMounted(() => {
  if (someRef.value?.content) {
    // @ts-ignore
    render('div', someRef.value.content)
  }
})

if you want to insert a component you can use the it like this:

const someRef: Ref<HTMLTemplateElement | undefined> = ref()
onMounted(() => {
  if (someRef.value?.content) {
    // @ts-ignore
    render(h(SomeComponent, { someProp: someValue }), someRef.value.content)
  }
})

Maybe there is a better, but for now that works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM