Using Vue 3 to transfer data within the <slot> element

My Objective:
I want to showcase an image from a dynamic link in Post.vue using the layout of PostLayout.vue

Within PostLayout.vue, there is a <slot> called postFeaturedImage. Inside that slot, there is a <div> where I intend to set the image as the background.

The Tools I'm Using: Laravel, InertiaJS, Vue 3

Here are my Code Snippets:

Post.vue:

<template>
    <PostLayout>
        <template #postfeaturedImage>
            <!-- The image should be displayed here -->
        </template>
    </PostLayout>
</template>

<script>
import PostLayout from '@/Layouts/PostLayout'

export default {
    data() {
        return {
            featured_image: ''
        }
    },
    components: {
        PostLayout,
    },
    props: {
        post: Object /* Received as prop from Controller */
    },
    mounted () {
        this.featured_image = this.post.featured_image
    }
}
</script>

PostLayout.vue:

<template>
    <slot name="postfeaturedImage" :bgImage="bgImage">
        <div :style="`background-image:url(${bgImage}); height: 75vh;`"></div>
    </slot>
    
</template>

<script>
    export default {
        
    }
</script>


I've condensed my code for clarity. As I navigate the world of Vue 3 and Inertia, any assistance would be greatly appreciated!

Answer №1

One potential solution involves the development of a custom FeaturedImage component. By directly referencing the post image within the props you receive, there is no need to utilize the data method or the mounted lifecycle hook in this scenario.

<template>
   <PostLayout>
      <template #postfeaturedImage>
         <FeaturedImage :src="post.featured_image" />
      </template>
   </PostLayout>
</template>

<script>
import PostLayout from '@/Layouts/PostLayout'
import FeaturedImage from '@/Layouts/FeaturedImage'

export default {
   components: {
      PostLayout,
      FeaturedImage
   },
   props: {
      post: Object
   }
}
</script>

Answer №2

Make sure to add a prop in your PostLayout.vue file

<script>
export default {
  props: {
    bgImage: { type: String },
  },
};
</script>

Then, assign a value to that prop in your Post.vue file

<template>
    <PostLayout :bgImage="featured_image"> </PostLayout>
</template>

If you ever need to create a post without an image and with a different layout, follow these steps:

<template>
    <PostLayout>
      <template #postfeaturedImage> post without background image</template>
    </PostLayout>
</template>

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

Tips for effectively utilizing nodejs soap

Here's the code snippet I've been working on: soap.createClient(url, function(err, client) { if(err) { res.status(500); return res.send(err); } client.GetMemberPIN({pUserName: 'r'}, function(error, result) { if(erro ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

Establish the starting time for the timer and use the setInterval() function according to the seconds stored within the object

How can I configure the values of timerOn, timerTime, and timerStart to make the watch start counting from 120 seconds? Currently, the clock starts counting from 3 minutes and 22 seconds, but it should start from 2 minutes. You can find all the code here: ...

What approach can be taken to establish a dependency between an AngularJS controller and a value that is retrieved through ajax and loaded onto the root

I have an app that loads like this: app.js file: angular.module('App', []).run(['$rootScope', '$q', 'SessionManager', 'EndpointService', function ($rootScope, $q, SessionManager, EndpointService) { $r ...

Issues with Firefox and FCKeditor displaying cftextarea on a single device

On a single computer in our network, the cftextarea is not rendering properly in Firefox 41.0.2. The Firebug console displays errors only on that specific computer; SyntaxError: missing } after function body fckeditorcode_gecko.js:108:329 ReferenceError: ...

Is there a way to retrieve the final elements from a deeply nested array?

I've been struggling to extract the last item from a nested array of objects. I've tried using methods like flatMap, flat, filter, and splice, but so far haven't had any luck getting the desired array. const array = [ [ { total_c ...

AngularJS: Share event from the parent component exclusively with its child components

I am looking to establish a way to broadcast an event from a parent directive to a specific child, without all children in every instance of the "parent" directive receiving it when using scope.broadcast in the parent directive link function. Current Beha ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...

Unable to connect to Server API endpoint

Encountering an issue while trying to access the API endpoint from server.js that connects to Spotify API. Below is my server.js code: // server.js const express = require('express'); const app = express(); const dotenv = require('dotenv&apo ...

Guide to importing images (.svg, .png) into a React component

I'm currently facing an issue trying to upload an image file in one of my React components using webpack. My project is already set up with web pack. Below is the code snippet for the component: import Diamond from '../../assets/linux_logo.jpg& ...

What is the best way to incorporate the .top offset into a div's height calculation?

Looking to enhance the aesthetic of this blog by adjusting the height of the #content div to match that of the last article. This will allow the background image to repeat seamlessly along the vertical axis. I attempted the following code: $(document).re ...

Text input in Bootstrap not reaching full width

Trying to achieve a Bootstrap textfield embedded in a panel that spans 100% of the remaining space-width within the panel. However, this is the result obtained: The blue border represents the edge of the panel. Below is the code being used: <div clas ...

Vuejs - Expanding Panels

Trying to implement an accordion using Vue.js has been a bit challenging for me. While I came across some examples online, my requirements are slightly different. In order to maintain SEO compatibility, I need to use "is" and "inline-template", which make ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Troubleshooting the issue of CSS animations activating twice and causing a flickering effect specifically in the Firefox browser

I am facing an issue with CSS animations in Firefox. When I try to slide in some radio buttons upon clicking a button, the animation seems to be firing twice in Firefox while it works fine in Chrome. I have attempted several solutions but haven't been ...

Following the implementation of the YITH ajax navigation filter, my jQuery scripts are no longer functioning as

I'm having trouble with using yith ajax navigation in my theme. Everything works perfectly until I click on an element to filter, at which point my jquery codes stop working. The team at yith suggests: If your product list contains JavaScript cod ...

Ways to retrieve the date of the chosen <td> cell in a calendar

Looking for a way to extract dates from the <td> elements selected by mouse? Here is my code snippet that highlights the TD upon selection: $(function () { var isMouseDown = false, isHighlighted; $("#schichtplan td") .moused ...

What are the common reasons for jQuery Image Slider malfunctioning?

After following a tutorial on Youtube (https://www.youtube.com/watch?v=KkzVFB3Ba_o) about creating a JQuery image gallery, I realized that my implementation is not working at all. Despite carefully reviewing my code and fixing any errors I could find, the ...

Using VueJS to Modify the Accessibility of Individual Inputs within a v-for Loop

I'm facing a challenge with enabling/disabling specific inputs on button click. The issue is that when I click the button, all inputs get enabled/disabled instead of just targeting one. My code uses props called "articles" which provide the ID, title ...

Executing a Shortcode Using a Button in Visual Composer for Wordpress

It should be easy to do this. I've got a great plugin with a modal newsletter signup form that offers various launch options, including manual launching with the following codes. https://i.stack.imgur.com/IGbsp.png My theme utilizes Visual Composer. ...