Navigating Vue 3's slot attributes: A step-by-step guide

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.

Answer №1

When working with Vue 3, it's important to remember that this.$slots.default is actually a function that needs to be called in order to return the nodes array. Additionally, make sure you are utilizing the props object instead of attrs:

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

View LIVE DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conflict in the naming and scoping of IE7 and IE8

While reviewing some code, I encountered a problem in Internet Explorer 7 and 8. Despite the constructor executing properly when stepped through, upon returning I received an error stating "Object does not support this property or method." How frustrating! ...

Displaying images dynamically in Angular using ng-repeat with URL strings

I'm working on a project where I need to dynamically call pictures inside an ng-repeat loop. Initially, I tried adding a key/value pair of 'img' to the JSON object I'm fetching and then dropping it inside the URL. However, this approach ...

Troubleshooting a Simple JavaScript Game: Mastermind Edition

Currently, I am working on a JavaScript version of the well-known board game "Mastermind". I have been facing some fundamental issues, mainly with JavaScript arrays and how to reference their values or elements. Despite spending quite a bit of time trying ...

Display solely the error message contained within the error object when utilizing the fetch API in JavaScript

I am facing an issue in logging the error message to the console while everything else seems to be working fine. Specifically, I am unable to log only the message such as "email exists" when the email already exists in the system. const submitHandler = a ...

Switching Perspective on Live ExpressJS Path -- Node.JS

I previously set up an express route with a template. Here's the code: app.get('/route', function route(req, res) { db.get('db_ID', function compileAndRender(err, doc) { var stream = mu.compileAndRender('theme-file.e ...

Understanding 'this' in ChartJS within an Angular application

Here is my event handler for chartJS in Angular that I created: legend: { onClick: this.toggleLegendClickHandler After changing the text of the y scale title, I need to update the chart. I am looking to accomplish this by calling this._chart.cha ...

How to change the color of a row in Jquery selectize using its unique identifier

Is it possible to assign different row colors for each value in the jquery selectize plugin? I would like to set the row color to green if the ID is 1 and red if the ID is 0. This is my selectized field: var $select = $('#create_site').selecti ...

Experiencing erratic outcomes with window.innerWidth in Mobile Safari

I am currently using JavaScript to determine the width of the browser: $(document).ready(function(){ var width = window.innerWidth; }); However, it seems that this method is producing inconsistent results. To showcase the issue, I have created a fun ...

How can we dynamically showcase a table column/row containing data with varying sizes of nested arrays?

I am struggling to showcase the data retrieved from firestore on a table using Vue.js and Element UI. Most solutions I found are for displaying a fixed amount of data, but my case involves an uneven number of data entries. Here is the structure of my data ...

Strange sudden increase in zoom between 1904 pixels and 1903 pixels

Currently, I am working on a Vue project that utilizes the Vuetify library. During my development process, I came across an unusual zoom jump between 1904px and 1903px. These sizes do not align with any predefined styles like md or lg. I am curious as to ...

What is the best way to adjust and filter an array based on a single value?

Here is an array that needs to be modified: [ {name: "test", value: "test", group: 0}, {name: "test1", value: "test2", group: 0}, {name: "test3", value: "test3", group: 1}, {name: "te ...

Show information according to the selection made in the dropdown menu

Greetings! I am currently developing a web app using MVC .NET (C#) that includes a registration page for two types of users, type 1 and type 2. In the form, there is a dropdown list where users can select their type. When selecting type 2, I would like t ...

prevent unnecessary duplicate database queries for generating metadata in the upcoming 13 or 14 instances

In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata. However, a drawback of this approach is that because of the separation of logic, fetching data base ...

Explore three stylish ways to showcase dynamic JavaScript content using CSS

Objective: For Value 1, the CSS class should be badge-primary For Value 2, the CSS class should be badge-secondary For all other values, use the CSS class badge-danger This functionality is implemented in the handleChange function. Issue: Current ...

How can I use D3.js to form a circular group in an organization structure, link it with a circular image, and connect

Is it possible to create a radial grouped circle using d3.js, similar to the image below: I have written some code as shown below. However, I am facing challenges in connecting every circle with a curved line and displaying a tooltip when hovering over a ...

Extract the content from the division and set it as the image source

Looking for a way to retrieve the content from a div and insert that into the 'src' parameter of an image. Working on a project where JSON is used to load translation files, preventing me from loading images directly, but I want to at least load ...

Tips for styling links in Nuxt/Vue based on specific conditions

Struggling with conditional styling in my Nuxt app. I want to change the background color of the active link based on the current page. Using .nuxt-link-exact-active works for styling the active link, but how can I customize it for each page? The links ar ...

Verifying the name's uniqueness and disregarding it in case of any alterations

I am currently working on a form that includes a modal to allow users to modify their name and email address. The issue I am facing is that the form sends a request to the server to check for unique values in all cases. While this is appropriate when creat ...

What is the best method to determine if a text box is filled or empty?

I need to verify whether a text box is populated with a name. If it is empty, an alert message should be shown upon clicking the submit button, and the page should not proceed with submitting the blank value. If there is a value in the text box, then that ...

"How to retrieve the height of an element within a flexslider component

I need some assistance with using JavaScript to determine the height of an element within a flexslider. There are two challenges I am facing. When I attempt to use a regular function getHeight(){ var h = document.getElementById("id-height").style.height; ...