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

Display various child components in a React application depending on the current state

I'm currently developing a brief React quiz where each question is represented as an independent component. I aim to swap out the current question component with the next one once a question is answered. Here's the present state of my root compon ...

How can we dynamically navigate to the next line within the Material UI DataGrid component when space is limited?

Currently, I am working with the datagrid component from material ui. I have retrieved some data from a database and am attempting to pass it to the datagrid component. However, I have noticed that certain fields contain long strings which do not fully app ...

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

Using JSP to send variables from an external Javascript file

After creating a timer function, I am looking to display the results on a different page. The setup involves a JSP file calling functions from a separate JS file in order to output the information to another screen: Instructions in the JSP file: <butt ...

Modify the value of a CSS property through JavaScript

Hey there, I'm wondering how to change a CSS value of the document itself, rather than targeting a specific element. I've already looked into solutions like Change :hover CSS properties with JavaScript, but they all involve adding CSS rules. I a ...

Leverage the key-value pairs in JSON to automatically suggest types within the function parameters

If we have data structured like this: { "key1": "hardcoded string", "key2": "another hardcoded string", } Imagine a function with 2 parameters where the first parameter should refer to key1 and the second to i ...

"Implementing constraints in Postgres using Node.js

Currently, I am struggling with writing a constraint code to handle situations where a user tries to search for an id that does not exist in the database (specifically PostgreSQL). Despite my efforts, the if statement in the code below does not seem to be ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Modifying the nested data organization in Sequelize

I'm looking to adjust the data structure retrieved from an ORM query involving four tables. The product and category tables have a many-to-many relationship, with the product_category table serving as a bridge. Additionally, there's a fourth tabl ...

Eliminate all blank spaces at the top and bottom of Span by squishing it

Imagine I have this code snippet: <span class="labels" style="background-color: #FFFFFF;border: 1px solid #000000;font-family: Verdana;font-size: 11px; ">74.58 ft.</span> I am looking for a way to compress the span element so that only the te ...

Is it possible for me to introduce an additional variable to the String.prototype object?

I have a question that has been bugging me out of curiosity. I was thinking about whether I can add an additional variable in front of String.prototype. For instance: $.String.prototype.functionName = function(){}; Obviously, this doesn't work as i ...

Utilize the identical ReactJS hook across multiple components

I've created a hook that pulls data from an API and stores the result in my component's state using setAllCommunitiesFromSponsor. Now I want to use this same hook in another component. Instead of copying and pasting, what is the best way to imp ...

Tips for configuring a file using javascript and angular.js

I am in need of some assistance. I would like to create a configuration file that stores all the paths for JavaScript files, which can then be dynamically called and included in the index page using Angular.js or JavaScript. The structure of my files is ex ...

What is the best way to set a value in PHP that can be utilized as flight plan coordinates on a Google Map within my script?

I am looking to dynamically update the content of my div with id "map" in response to button clicks, where the flight plan coordinates are changing. Currently, I have attempted to achieve this by assigning PHP output to a JavaScript variable as shown below ...

Tips for fixing the "Uncaught TypeError: Cannot access property 'get' of undefined" error in Vue.JS 2

Here is my component: methods: { reloadMessage() { setTimeout(function () { this.$http.get(window.BaseUrl + '/message/inbox'); }, 1500); } } And here are my routes: Route::group(['prefix' => &ap ...

Angular service providing a subset of resource data

I am currently working with an Angular factory called DogePrice: .factory('DogePrice', ['$resource', function ($resource) { return $resource("https://chain.so/api/v2/get_info/DOGE"); }]) Usually, the API response looks like this: ...

Transformation of visuals with alteration of status

I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...

The issue of why iterating over an array of objects does not function properly in React JS

P.S: I have made some modifications to the code below. Extracting the doctor's value from JSON data, updating the state, and then mapping it to print out the values. Initially, there is only one doctor, but in the future, there could be more than one ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...