Guide to generating an array of slot indexes within Vue.js

In the process of developing my personalized carousel, I have chosen to incorporate images using the <img> tag. However, I find that utilizing the Vue method for creating a carousel component offers more flexibility, especially since I intend to integrate a LightBox component within the slots of my carousel.

Let me introduce you to my parent component - the carousel:

<template>
    <div class="carousel">
        {{ slides }}
        <slot></slot>
</div>

</template>
<script>
import { ref } from 'vue';
export default{
    data(){
        return{
            Currentslide: 0,
        }
    },
    setup(props, {slots}){
        const slides=ref(slots.default().map((slides) => slides.props.id))
        return{
            slides,
        }
    }
}

</script>

Now, let's delve into the child component - the slide:

<template>
    <div class="slide">
        <slot/>
    </div>
</template>
<script>

</script>
<template>
<Carousel>
  <Slide id="1">1243423</Slide>
  <Slide id=2>
    1231
  </Slide>
  <Slide id="3">r445</Slide>
</Carousel>
</template>

<script>
import Carousel from "../../components/Reusable components/Carousel.vue"
import Slide from "../../components/Reusable components/Slide.vue"
export default{
  components:{
    Carousel,
    Slide
  }
}

While there may be inefficient methods in existence, such as creating an array of slot indexes, it is not considered the optimal solution. Hence, I am determined to explore alternate approaches for extracting IDs from slots within Vue.js frameworks.

Answer №1

Is the utilization of slots really necessary? I believe a simpler approach can be implemented.

Check out the playground

const { createApp } = Vue;

const MyImg = {
  props: ['src'],
  template: '<img :src="src" class="image" />'
}

const MyGallery= {
  components: { MyImg },
  props: ['images'],
  data() {
    return {
        current: 0
        }
  },
  methods: {
    prev() {
      this.current--;
      if (this.current < 0) this.current = this.images.length - 1;
    },
    next() {
      this.current++;
      if (this.current > this.images.length -1) this.current = 0;
    }
  },
  template: '#my-gallery'
}

const App = { 
  components: { MyGallery },
  data() {
    return {
        images: [
        'https://images.unsplash.com/photo-1517423568366-8b83523034fd?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=300&q=80',
        'https://images.unsplash.com/photo-1609910063430-33fc20be9f88?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=300&q=80',
        'https://images.unsplash.com/photo-1576138089064-2ca7edab2f49?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=300&q=80',
        'https://images.unsplash.com/photo-1612637306950-fd33786d912e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=300&q=80'        
        ]
    }
  }
}
const app = createApp(App)
app.mount('#app')
#app { line-height: 2; }
[v-cloak] { display: none; }
label { font-weight: bold; }
.container {
  min-height: 320px;
}
.image {
  max-width: 300px;
  max-height: 300px;
  position: absolute;  
}

.slide-left-enter-active,
.slide-left-leave-active {
  transition: all 0.3s ease-out;
}

.slide-left-enter-from {
  opacity: 0;
  transform: translateX(150px);
}

.slide-left-leave-to {
  opacity: 0;
  transform: translateX(-150px);
}
<div id="app">
<div class="container">
  <my-gallery :images="images">
  </my-gallery>
</div>
<p>Pictures &copy Unsplash</p>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script type="text/x-template" id="my-gallery">
<button @click="prev()">&lt;</button> Bild {{current + 1}}
  <button @click="next()">&gt;</button>
  <br />
  <transition-group name="slide-left">
    <my-img v-for="(img, index) in images" v-show="current == index" :key="index" :src="img">
    </my-img>
  </transition-group> 
</script>

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

Redis: Unable to establish a connection as net.connect is not recognized as a

I'm struggling to integrate Redis with nodejs Encountering issues during execution Despite using the same code, I am facing this error: Here's my code snippet: import { createClient } from 'redis' export const client = createClient({ ...

Encountering the error message "Unable to access properties of undefined (specifically 'commit') in NUXT"

I'm encountering a roadblock as a newcomer to Vue. My goal is to capture user input data from a form and transfer it to a Vuex store. Once in the Vuex store, an action will trigger (fetching from an API) and I aim to retrieve that data back into my ap ...

Achieve a smooth sliding effect for a div element in Vue using transition

When utilizing transitions in conjunction with v-if, it appears that the div is initially created and then the animation occurs within that div. Is there a way to have the div move along with the text during the animation? For example, when clicking on th ...

Setting up VueRouter with Vue-Cli Webpack is an essential step in building

After initializing a new project with the vue-cli command: vue init webpack myapp I am attempting to incorporate vue-router for managing routes, but facing challenges. Below is my main.js: import Vue from 'vue' import VueRouter from 'vue ...

Discovering the automatically generated routes in Nuxtjs

Can I access the route list created by Nuxt.js based on pages folder items? The issue is that I am unsure of the exact route name generated for each component. $router.push({name: 'no-idea-what-the-route-name-is', query: { id: data.id } }) This ...

Configuring CSP in NUXT

Encountering CSP blocking with my local js files. Below is my nuxt.config.js: unsafeInlineCompatibility: true, policies: { 'default-src': ["'self'", 'delivly.com', 'localhost', '*.gstatic.co ...

unable to store user input in a REST API using the store functionality

Welcome to my main page! Here, I have a form that I am looking to connect with an API in order to store the entered data: <div> <span>User ID</span> <input type="text" v-model="info.userId"> </div> <br> <div> ...

How to leverage Vue Selectize to fetch JSON data from dropdown options?

I have integrated vue2-selectize to showcase a list of options fetched via an axios call: <template> <selectize v-model="selected" :settings="settings"> <option v-for="option in options" :value="option.id"> ({{ op ...

Display an error message when the button is clicked and the input field is left empty in a Vue 3 script setup

Hello, I am currently exploring Vue 3 and embarking on a new Vue 3 project venture. However, I seem to be encountering a challenge when it comes to displaying an error message if the button is clicked while the input field remains empty in my Vue 3 script ...

Tips for efficiently passing TypeScript constants to Vue templates without triggering excessive reactivity

I'm curious about the most efficient way to pass a constant value to a template. Currently, I am using the data property in Vue, but I believe that is better suited for state that changes over time as Vue adds event listeners to data properties. The c ...

How can you align the label of a v-text-field to the right in rtl languages?

I am working with a v-text-field in the following format: <v-text-field v-model="username" label="نام کاربری" /> However, I have noticed that the label appears on the left side. Is there a way to adjust it so that it displays on the right ...

Guide on setting up a dynamic sidebar linked to the route in Nuxt.js

My pages folder is structured like this: pages/ --index/ ----page1/ ------_slug.vue ----page2/ ------_slug.vue ----page1.vue // contains different content ----page2.vue // contains different content --index.vue The routes can be accessed as follows: /i ...

The specified dependency, * core-js/fn/symbol, could not be located

I am in the process of developing a Vue.js application with Vuex and have encountered some errors during the build. I attempted to resolve the issue by installing npm install --save core-js/fn/symbol, but unfortunately, it did not work as expected. https:/ ...

Capturing content from an HTML node and integrating it into VueJS data

<tasks> @foreach ($task as $tasks) <task>{{ $task->name }} [{{ $task->completed }}]</task> @endforeach </tasks> This snippet shows how I display a list of tasks from the database. Here is my Vue component setu ...

Unable to successfully retrieve the output from a function within an AJAX request

Hey, I'm having trouble getting the value from this function. It keeps returning undefined and I can't figure out why. Here's the code snippet: function getData() { axios.get('/task') .then(response => { ...

Displaying HTML content from a Vuejs response within a Dialog box

After receiving a response from the server via a REST request in HTML format, I have saved it in a data:[] variable. When I log this data on the console, it appears as raw HTML code. This reply is currently stored as a String, and my challenge now is to co ...

Utilizing multiple address parameters within a single-page application

Apologies for the lengthy post. I have encountered an issue with my code after running it through a bot that I can't seem to resolve. In my code, I aim to create functionality where you can visit the address #two, followed by two separate parameters ...

Issue arises when annotation is utilized in ChartJs, as the tooltip fails to appear

Upon hovering over a dot, only a blue line is displayed without showing a tooltip as expected below: Library Version: "chart.js": "^2.9.3", "chartjs-plugin-annotation": "^0.5.7" Actual : enter image descriptio ...

Webpack and Vue.js: Error - Definition missing for template or render function

I am encountering an issue while attempting to load a component in my root Vue instance. The error message I receive is displayed above. Below is the content of the main.js file: "use strict"; require('./../shared/bootstrap'); // loads jquery, ...

Ways to access and retrieve data from Vuex store values?

Combining vuex and vuejs 2 for the first time. I'm a beginner with vuex and I need to monitor changes in a store variable. Trying to implement the watch functionality within my vue component. This is my current code snippet: import Vue from ' ...