You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中如何将插槽内容转换为HTML字符串?

如何将Vue插槽的VNode转换为HTML字符串传递给组件Props?

我需要把父组件传入的插槽内容转换成HTML字符串,传给一个接收HTML字符串并渲染的包裹组件的content属性。相关代码如下:

Parent.vue

<Ellipsis style="max-width: 240px"
  >Genes that helped people survive during the time of the Black Death are
  more likely to be found in people with autoimmune diseases alive today.
  Does this tell scientists anything about what surviving the COVID-19
  pandemic might mean for the world’s population?
  <template #tooltip>
    <div style="text-align: center">
      <i>Lorem Ipsum</i><br />
      Sed ut perspiciatis unde omnis<br />
      iste natus error sit voluptatem accusantium doloremque
      laudantium,<br />
      totam rem aperiam
    </div>
  </template>
</Ellipsis>

Ellipsis.vue

<template>
  <Tooltip
    ref="tooltipRef"
    :content="tooltipContent"
  >
    <span
      ref="content"
      :class="ellipsisClassRef.valueOf()"
      :style="ellipsisStyleRef"
      @click="handleClickRef"
    >
      <slot></slot>
    </span>
  </Tooltip>
</template>

<script setup>
import { onMounted, ref } from 'vue';

const tooltipContent = ref('');

onMounted(() => {
  if (slots.default !== undefined) {
    tooltipContent.value = slots.default()[0].children;
  }
  if (slots.tooltip !== undefined) {
    // 需要替换成插槽对应的HTML字符串
    tooltipContent.value = `<div style="color: blue">hello world</div>`;
  }
});
</script>

核心问题:打印slots.tooltip()得到的是嵌套的VNode对象,手动拼接HTML字符串效率极低,有没有简便方法直接把插槽内容转换成<div style="text-align: center"><i>Lorem Ipsum</i>...</div>格式的HTML字符串?


解决方案

方法1:使用Vue官方renderToStringAPI

Vue的@vue/server-renderer包提供了renderToString方法,可直接将VNode渲染为HTML字符串,步骤如下:

  1. 安装依赖:
npm install @vue/server-renderer
  1. 在Ellipsis.vue中修改逻辑:
<script setup>
import { onMounted, ref } from 'vue';
import { renderToString } from '@vue/server-renderer';

const tooltipContent = ref('');

onMounted(async () => {
  if (slots.tooltip) {
    // 获取插槽的根VNode
    const tooltipVNode = slots.tooltip()[0];
    // 将VNode转换为HTML字符串
    tooltipContent.value = await renderToString(tooltipVNode);
  }
});
</script>

方法2:客户端临时渲染DOM提取HTML

不想引入额外依赖的话,可以临时创建DOM容器渲染插槽内容,再提取HTML:

<script setup>
import { onMounted, ref, render } from 'vue';

const tooltipContent = ref('');

onMounted(() => {
  if (slots.tooltip) {
    const tooltipVNode = slots.tooltip()[0];
    // 创建临时DOM容器
    const tempContainer = document.createElement('div');
    // 渲染VNode到容器
    render(tooltipVNode, tempContainer);
    // 提取HTML字符串
    tooltipContent.value = tempContainer.innerHTML;
    // 清理临时DOM
    render(null, tempContainer);
  }
});
</script>

注意事项

  • 两种方法都会渲染插槽当前状态的内容,包含动态绑定的数据或组件的实时状态。
  • 若插槽有多个根VNode,建议先包裹一个父元素再转换,避免HTML结构混乱。

内容的提问来源于stack exchange,提问作者Kai021195

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:20:41