Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue slots with variable HTML passed in

I have a string that contains some HTML markup.

I would like to pass this into a component's slot.

This component is used elsewhere with regular html markup between the opening and closing tags, and works as expected.

The issues are that mustache syntax outputs escaped HTML, {{myFormattedText}} becomes literally Some line of <span>text with formatting</span> that is passed in from somewhere else which is not what we want.

Passing it in the v-html="myFormattedText" attribute on the component replaces all content inside the component tags with the variable string.

Is there a way to do this? I'd like to reuse this component, for visual consistency reasons, but the content that we receive for it is disparate and varies widely based on the view or source.

Test string:

myFormattedText = "Some line of <span>text with formatting</span> that is passed in from somewhere else";

Component:

<template>
    <div class="doing-a-thing">
        <h2>Some text</h2>
        <div class="thing">Random stuff</div>
        <slot></slot>
    </div>
</template>

Attempts:

<mycomponent>{{myFormattedText}}</mycomponent>
<mycomponent v-html="myFormattedText"></mycomponent>
like image 662
Randy Hall Avatar asked Dec 22 '25 00:12

Randy Hall


1 Answers

Just put the v-html render on an element inside the component tags and it'll get rendered correctly and passed in.

<mycomponent><div v-html="myFormattedText"></div></mycomponent>

Again, moments after posting, it hits me like a bolt of lightning...

like image 80
Randy Hall Avatar answered Dec 25 '25 03:12

Randy Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!