【问题标题】:Render slot as v-html (Vue 3)将插槽渲染为 v-html (Vue 3)
【发布时间】:2022-10-06 21:58:54
【问题描述】:

目标

如何实现呈现作为插槽传递的 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]

Link to playground

使用道具的解决方法

作为一种解决方法,我们当然可以使用道具,但它很冗长。

// 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>

    标签: vue.js


    【解决方案1】:

    slots.default() 返回您传递的插槽元素的数组,尝试映射该内容并呈现它:

    h("p", {
       innerHTML: slots.default().map(el=>el.children).join(''),
      });
    

    Playground

    【讨论】:

      【解决方案2】:

      你可以在 div v-html 中传递它:

      <MyComponent>
        <div v-html="htmlStr" />
      </MyComponent>
      

      【讨论】:

        猜你喜欢
        • 2018-12-03
        • 1970-01-01
        • 2017-02-27
        • 2021-09-19
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 2021-09-15
        • 2020-07-11
        相关资源
        最近更新 更多