[Vuejs]-VueJs: Component slot as property

0👍

You should use v-html inside of the call-dialog component to insert the raw HTML from the message prop into an element.

<div v-html="message"></div>

https://v2.vuejs.org/v2/api/#v-html

0👍

I’ve had to do something similar for a custom button component.

Vue.prototype.$getSlotText = function( name = 'default' ) {
    const htmlElements = this.$slots[name];
    if(!htmlElements || !htmlElements.length) return '';

    return htmlElements.reduce((fullText, {tag, text}) => {
        return fullText + (tag === 'br' ? '\n' : text || '');
    }, '');
}

Essentially, this would access the HTML-Elements on the "default" slot (by default).

  • If none found, returns '' blank string.
  • If some found, iterates over each Element, concatenates it’s text property if found, or \n if it’s a <br/> tag.

Note: The .reduce(...) method is used for the iteration / concatenation. Alternatively a .map(...) call with a similar arrow-function, followed by a .join('') would probably result the same thing.

Leave a comment