What is the best method for retrieving data from a loop in a vuetify carousel?

I am using vuetify to create a carousel that displays recipes stored in the database. However, I would like the carousel to expand below with all the details of the recipe when clicked. After some research, I found a Vuetify component that fits my requirement perfectly: Vuetify Carousel

The issue arises when using the v-slide-item within a loop to retrieve recipe data. Due to the v-expand-transition, I lose access to this loop. How can I display the recipe data accordingly?

Below is the code snippet :

<template>
    <v-sheet
        class="mx-auto"
        elevation="8"
        max-width="100%"
        style="box-shadow: none !important;"
    >
        <v-slide-group
            v-model="model"
            class="pa-4 slider"
            show-arrows
        >
            <v-slide-item
                v-for="n in Object.keys(recipes)"
                :key="recipes[n].id"
                v-slot="{ active, toggle }"
            >
                <v-card
                    :color=" 'grey lighten-1'"
                    class="ma-4 card-recipe"
                    height="200"
                    width="200"
                    style="border-radius: 10px;"
                    v-bind:style="recipes[n].recipe[0].first_recipes_image != null ? {  backgroundImage: 'url(' + recipes[n].recipe[0].first_recipes_image + ')' } : {  backgroundImage: 'url(https://cdn.vuetifyjs.com/images/cards/sunshine.jpg)' }"
                    @click="toggle"
                >
                    <p class="card-text" ><span class="black--text">{{ recipes[n].recipe[0].name }}</span></p>
                    <v-row
                        class="fill-height"
                        align="center"
                        justify="center"
                    >
                        <v-scale-transition>
                            <v-icon
                                v-if="active"
                                color="white"
                                size="48"
                                v-text="'mdi-close-circle-outline'"
                            ></v-icon>
                        </v-scale-transition>
                    </v-row>
                </v-card>
            </v-slide-item>
        </v-slide-group>

        <v-expand-transition>
            <v-sheet
                v-if="model != null"
                height="200"
                tile
                style="background-color: #FFF8F0 !important;"
            >
                <v-row
                    class="fill-height"
                    align="center"
                    justify="center"
                >
                    <h3 class="text-h6">
                        Selected {{ model }}
                    </h3>
                </v-row>
            </v-sheet>
        </v-expand-transition>
    </v-sheet>
</template>

<script>
    import { mapGetters } from "vuex";

    export default {
        props: {
        },
        data: () => ({
            model: null,
            recipes: [],
            openedCards: [],
        }),
        computed: {
            console: () => console,
            ...mapGetters({
                plantActive: 'permatheque/getPlant',
            }),
        },
        methods: {
           async getPlantRecipes() {
          this.$axios
            .$get("/lnk/plant/recipes?plant_id=" + this.plantActive.id + "")
            .then((response) => {
              this.recipes = response;
              console.log(this.recipes);
            })
            .catch((error) => {
              console.log(error);
            });
    },
        },
        mounted() {
            this.getPlantRecipes()
        }
    }
</script>

If you have any further questions, feel free to ask! Thank you.

Answer №1

Utilize the v-model feature of the v-slide-group to easily access the index of the selected item in the carousel from the recipes array.

This functionality allows you to identify which recipe is currently selected, enabling you to quickly retrieve the corresponding recipe information from the array or make an additional API call to fetch the data.

Illustrative Example:

Take a look at this interactive codesandbox I created: https://codesandbox.io/s/stack-71474788-recipes-carousel-6vm97o?file=/src/components/Example.vue

If your recipes array already contains the necessary recipe details, simply utilize the v-model variable of the v-slide-group, labeled as

recipeIndex</code, to directly access the data stored within your array.</p>
<pre><code><v-expand-transition>
    <v-sheet v-if="recipeIndex != null" tile style="background-color: #FFF3E0 !important;">
        <v-container fluid class="pa-12">
            <v-row>
                <v-col cols="12" sm="6">
                    <span class="text-h6">{{ `${recipes[recipeIndex].name}'s Recipe` }}</span> <br>
                    <span class="text-subtitle-1">{{ recipes[recipeIndex].description }}</span>
                    <p class="text-justify mt-4">
                        {{ recipes[recipeIndex].steps }}
                    </p>
                </v-col>
                <v-col cols="12" sm="6" class="d-flex align-center justify-center">
                    <div class="thumbnail">
                        <img :src="recipes[recipeIndex].image" alt="Beach Scene" style="width: 100%;" />
                    </div>
                </v-col>
            </v-row>
        </v-container>
    </v-sheet>
</v-expand-transition>

To retrieve information from a secondary API call, you can establish a watcher on the recipeIndex variable to automatically gather the updated recipe details whenever it changes.

https://i.sstatic.net/5NvTr.png

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

Troubleshooting Azure Routing Issues after Switching to .ejs Files

I am facing an issue where my application breaks on Azure after changing the file extensions and routes to point to the renamed .ejs files, but it works perfectly fine locally. angularApp.js var app = angular.module('theApp', ['ui.router&a ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

Struggling with setting up the router

Presented below is the code snippet from my router/index.js file: import Vue from 'vue' import Router from 'vue-router' import Home from '../views/Home' import Login from '../views/Login' Vue.use(Router) export de ...

Parsley.js now supports the use of the attribute `data-parsley-errors

Currently, I am attempting to integrate the errors container (e.g., data-parsley-errors-container="#ErrorSummary") with parsley.js. Most aspects are functioning properly, but I've encountered an issue. Specifically, I am looking to solely adjust the ...

Is it possible to incorporate Vector4's into the geometry of three.js?

Exploring the functionalities of the three.js library has been a fascinating journey for me. As I delve into the intricacies, I've come to understand that the coordinates stored in a mesh's geometry are tuples consisting of (x,y,z). However, bene ...

What is the process for converting a CSV file to JSON format using node.js?

I am working on converting a CSV file from Clash Royale into an array. The CSV file has over 40 properties in its header or data. For example: name level count upgrade cost common 14 5, 20, 50, 100 rare 12 50, 150, 400, 1000 Below is my node.j ...

Encountering a TypeScript error when attempting to utilize indexOf on a Typed Array, leading to restriction

I have been working with an Interface, where I created an array of type Interface. I am currently facing some IDE error complaints when trying to use the .indexOf method on the Array. These errors seem confusing to me, and I'm hoping someone here migh ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

Trouble with window.location functionality following an AJAX request

After a successful response from an AJAX request, the window.location method is not working as expected. However, when I debug step by step in Firefox, the window.location works fine. function login(){ var jason ={"usuario":document.getElementById("inp ...

Adding custom CSS and JavaScript to the TYPO3 backend: A step-by-step guide

Is there a way to incorporate css and javascript files into the backend? I'm aiming to enhance custom created content elements with these files, making them more visually appealing for users. Platform: TYPO3 v9 Method: Composer Mode Purpose: Cu ...

Insert a new row in a table using jQuery

Could you help me figure out how to move an element within a table row into another table using jQuery? I've been considering using 'append', but it requires session handling. What is the best method in this case: should I use ajax, JSON, PH ...

Clicking a button in Angular JS to refresh a specific ID element

Just diving into AngularJS for my mobile web app development. I have different id divs for each view, as that's how AngularJS operates with one HTML page. My goal is to use specific javascript for each id page, as they need to retrieve JSON data objec ...

Discovering the Voice Channel of a User using Discord.js v13

I'm currently working on a 'wake up' command for my bot that should move the mentioned member between 2 specific voice chats and then return them to their original VC. I've successfully got the bot to move me between those 2 VCs, but no ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

Encountering a 415 Error while making an ajax call using formData

I am attempting to make an ajax call with formData that includes a list of image files and some strings. However, the call is not successful and I am receiving error 415. Here is the code: var file = picChooser.files[0]; var jobExecutionImagesContext = n ...

Retrieve the nearest attribute from a radio button when using JQuery on a click event

I have a query regarding the usage of JS / JQuery to extract the data-product-name from a selected radio button, prior to any form submission. Although my attempt at code implementation seems incorrect: return jQuery({{Click Element}}).closest("form" ...

I need to figure out how to nest a div inside of a ul-li-a and ensure that the text inside the

In my search button, I have a cached list of options. When I select one, it should trigger the menu and choose the correct option. However, I am having trouble comparing the innerText of a div with the selected option from the search area. Both a and div e ...

How do callback functions in Javascript interact with variables outside of their scope?

Greetings to all. I am facing an issue regarding the 'callback function - scope of variable', My intention is to utilize the 'i in for loop' with the 'callback function User_UidSearch', however, I am unable to implement it. ...

Navigate through a JavaScript text file one line at a time

There is a text file with the following content: User:root Password:root123 My goal is to read this text file in JavaScript line by line and store it in an array. Then, I want to split each value in the array using a colon (:). Despite trying multiple a ...