Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access slot attributes in Vue 3

I’ve got a Vue component named MediaVisual. That componant contains a slot.

The problem is that I am trying to get the src attribute of the passed in slot element.
But this.$slots.default appears to be undefined. Eventhough before (in version 2) I used this.$slots.default[0].attrs.src to get the slot’s SRC value.

This error happened since updating Vue to version 3… (it was version 2.5.7).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<template>
<figure :class="visualClass" :style="getPhotoBackgroundSrc()">

    <slot></slot>

    <div class="visual__text" v-show="this.show">
        <div class="visual__title">{{ title }}</div>
        <div class="visual__subtitle">{{ subtitle }}</div>
    </div>

</figure>
</template>

Here is the function inside methods:

 getPhotoBackgroundSrc() {
            let image_url = typeof this.$slots.default[0] !== 'undefined' ? this.$slots.default[0].attrs.src : '',
                css = '';

            if (this.position === 'center')
                css += 'background-position-y: center;';

            if (this.type === 'cover')
                css += ' background-image: url("' + image_url + '");';

            return css;
        },

Usage of slot:

<media-visual type="cover" title="" subtitle="">
     <img src="/photos/image.jpg" alt="" />
</media-visual>

So… what would be the correct way in Vue 3 to get the SRC attribute of a passed in slot element?

>Solution :

In Vue 3 this.$slots.default is a function which should be called to return the nodes array, also use props instead of attrs:

let image_url = typeof this.$slots.default !== 'undefined' ? this.$slots.default()[0].props.src : '',

LIVE DEMO

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading