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).
<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 : '',