Home  >  Q&A  >  body text

Vue adds content in #document-fragment

<p>I'm using vue3 with nuxt3 and want to add a template tag with content in the generated <code>#document-fragment</code>. The generated HTML should look like this: </p> <pre class="brush:php;toolbar:false;"><body> <template id="some-id"> #document-fragment <div> ... </div> </template> </body></pre> <p>When I use plain html it works great. In vue3, the element is not inside <code>#document-fragment</code> but below it, like this: </p> <pre class="brush:php;toolbar:false;"><body> <template id="some-id"> #document-fragment <div> ... </div> </template> </body></pre> <p>My vue3 code looks like this (similar to html code): </p> <pre class="brush:php;toolbar:false;"><template> <v-app> <template id="some-id"> <div></div> </template> </v-app> </template></pre> <p>Is there any way to put content into a <code>#document-fragment</code> element? </p>
P粉916760429P粉916760429415 days ago445

reply all(1)I'll reply

  • P粉594941301

    P粉5949413012023-09-01 00:07:29

    I solved this problem by using ref on the template tag and then using 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 it like this:

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

    There may be better ones, but it works for now.

    reply
    0
  • Cancelreply