Vue 在 #document-fragment 中添加内容
P粉916760429
P粉916760429 2023-08-31 09:43:47
[Vue.js讨论组]
<p>我将 vue3 与 nuxt3 结合使用,并希望在生成的 <code>#document-fragment</code> 中添加一个包含内容的模板标签。生成的 HTML 应如下所示:</p> <pre class="brush:php;toolbar:false;">&lt;body&gt; &lt;template id=&quot;some-id&quot;&gt; #document-fragment &lt;div&gt; ... &lt;/div&gt; &lt;/template&gt; &lt;/body&gt;</pre> <p>当我使用纯 html 时,效果很好。在 vue3 中,元素不在 <code>#document-fragment</code> 内部,而是在其下方,如下所示:</p> <pre class="brush:php;toolbar:false;">&lt;body&gt; &lt;template id=&quot;some-id&quot;&gt; #document-fragment &lt;div&gt; ... &lt;/div&gt; &lt;/template&gt; &lt;/body&gt;</pre> <p>我的vue3代码如下所示(类似于html代码):</p> <pre class="brush:php;toolbar:false;">&lt;template&gt; &lt;v-app&gt; &lt;template id=&quot;some-id&quot;&gt; &lt;div&gt;&lt;/div&gt; &lt;/template&gt; &lt;/v-app&gt; &lt;/template&gt;</pre> <p>有什么方法可以将内容放入<code>#document-fragment</code>元素中吗?</p>
P粉916760429
P粉916760429

全部回复(1)
P粉594941301

我通过在模板标记上使用 ref 然后使用 render 函数解决了这个问题。

<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)
  }
})

如果你想插入一个组件,你可以像这样使用它:

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

也许有更好的,但目前可行。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号