Search code examples
vuejs3vue-slot

How to pass prop to slot as HTML in vue 3?


I have an alert component

<template>
  <div class="notification is-light" :class="type" :style="cssProps">
  <button @click="emitClose" class="delete"></button>
    <slot></slot>
</div>
</template>

I want to be able to pass HTML into it via the slot, so that I can define exactly what the alert will look like, for example

<Alert v-if="showError" @close="showError = false" maxWidth="600px">
   <span>The next words <b>are bold</b> because of the b tag</span>
 </Alert>

The text I'm passing to the slot is rendered as HTML and the tags work as expected.

However, the text that I want to pass the the alert will be dynamically generated based on a response from an API, so I'm trying to to the following

//somewhere in my component javascript
this.error = '<span>Error connecting to your account. Try <b>closing this window</b></span>'

Then I'm calling the component as follows

<Alert>{{error}}</Alert>

This renders the pure text, including the html tags, as opposed to rendering the html tags as in the first example.

How can I achieve this?


Solution

  • It seems you need to use v-html directive to avoid HTML escaping. Try

    <Alert><span v-html="error"></span></Alert>
    

    Make sure the content is safe from XSS (doesn't contain any unsafe user input).
    Visit raw HTML documentation for more info.