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

如何实现将插槽中HTML字符串以v-html渲染的Vue组件

需求目标

如何实现一个组件,使其能够渲染通过插槽传入的HTML字符串(例如从CMS获取的),用法如下:

// app.vue
<script setup>
import MyComponent from "./MyComponent.vue"
const htmlStr = `not bold <b>bold</b>`
</script>

<template>
  <MyComponent>{{htmlStr}}</MyComponent>
</template>

原理说明

要渲染HTML字符串(例如从CMS获取的),我们可以使用v-html指令:

// app.vue
<script setup>
const htmlStr = `not bold <b>bold</b>`
</script>

<template>
  <p v-html="htmlStr"></p>
</template>

失败尝试

我曾尝试以下方案,但未成功:

// component.vue
<script>
import { h } from "vue";

export default {
  setup(props, { slots }) {
    return () =>
      h("p", {
        innerHTML: slots.default(),
      });
  },
};
</script>

该方案渲染结果为:

[object Object]

基于Props的替代方案

当然我们可以用Props作为替代方案,但这种方式较为繁琐:

// app.vue
<template>
  <MyComponent :value="htmlStr">{{htmlStr}}</MyComponent>
</template>
// component.vue
<template>
  <p v-html="value"></p>
</template>

<script setup>
import { defineProps } from 'vue'
  
defineProps(['value'])
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:41:12