传入可变 HTML 的 Vue 插槽

Ran*_*all 2 vue.js vue-component vuejs2

我有一个包含一些 HTML 标记的字符串。

我想将其传递到组件的插槽中。

该组件在其他地方使用,在开始和结束标记之间使用常规 html 标记,并且按预期工作。

问题是,mustache 语法输出转义的 HTML,{{myFormattedText}}变成了字面意思Some line of <span>text with formatting</span> that is passed in from somewhere else,这不是我们想要的。

将其传递到v-html="myFormattedText"组件的属性中会将组件标记内的所有内容替换为变量字符串。

有没有办法做到这一点?出于视觉一致性的原因,我想重用此组件,但我们收到的内容是不同的,并且根据视图或源的不同而有很大差异。

测试字符串:

myFormattedText = "Some line of <span>text with formatting</span> that is passed in from somewhere else";
Run Code Online (Sandbox Code Playgroud)

成分:

<template>
    <div class="doing-a-thing">
        <h2>Some text</h2>
        <div class="thing">Random stuff</div>
        <slot></slot>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

尝试:

<mycomponent>{{myFormattedText}}</mycomponent>
<mycomponent v-html="myFormattedText"></mycomponent>
Run Code Online (Sandbox Code Playgroud)

Ran*_*all 8

只需将 v-html 渲染放在组件标签内的元素上,它就会正确渲染并传入。

<mycomponent><div v-html="myFormattedText"></div></mycomponent>
Run Code Online (Sandbox Code Playgroud)

再次,发布后不久,它像一道闪电击中了我......