如何实现将插槽中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
相关产品推荐
相关产品推荐

