Currently, I am facing an issue with a Vue component named MediaVisual. This component contains a slot.
The problem arises when attempting to retrieve the src attribute of the slot element that is passed in. Surprisingly, this.$slots.default
shows up as undefined
. In the previous version (2.x), I used this.$slots.default[0].attrs.src
to access the SRC value of the slot.
This error seems to have occurred after updating Vue to version 3 from 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>
Below is the method implementation under methods
:
getPhotoBackgroundSrc() {
let image_url = typeof this.$slots.default[0] !== 'undefined' ? this.$slots.default[0].attrs.src : '',
css = '';
if (there are any specifics about positioning)
css += 'background-position-y: center;';
if (the requirement is for covering)
css += ' background-image: url("' + image_url + '");';
return css;
},
Slot Usage:
<media-visual type="cover" title="" subtitle="">
<img src="/photos/image.jpg" alt="" />
</media-visual>
Therefore, I am seeking guidance on the correct approach in Vue 3 to obtain the SRC attribute of a slot element that is being passed in.