Adjust the array index to display the following slide

<template>
    <div class="carousel">
        
        <slot></slot>
         <button @click="index++">Next</button>
    </div>

</template>
<script setup>
import { useSlots, onMounted, onUpdated, ref} from 'vue';

const slots = useSlots()
const index = ref(0)
onMounted(() => {
  const defaultSlotElements = slots.default()
  console.log(`The default slot contains ${defaultSlotElements.length} elements.`)
  
}),
onUpdated(() =>{
    console.log(defaultSlotElements[index])
}
)

</script>

I am working on creating a carousel using slots. With the help of an individual on Stack Overflow, I learned how to extract an array of slots. An additional challenge I am facing involves changing the index of elements in the array to navigate through the carousel slides. The plan is to update the slide component with the current slot selected, which defaults to 0. However, changing the value of the index with the v-on directive is not straightforward, as it needs to select the next or previous slot in the array. Despite the complexity of this vue subject, I prefer not to opt for a simpler carousel version based on image arrays due to limitations on adding additional components within this one.

It seems that simply changing the index arr[index] does not directly lead to selecting the next object in the array.

Answer №1

If you are adamant about using slots, the only option is to utilize Vue's Render Functions & JSX

<script setup>
import { useSlots, onMounted, onUpdated, ref, h} from 'vue';

const slots = useSlots()
const index = ref(0)
const current = ref(null)
onMounted(() => {
  const defaultSlotElements = slots.default()
  current.value = defaultSlotElements[0]
}),
onUpdated(() =>{
    console.log(defaultSlotElements[index])
    }
)  
const render = () => {
    return h('div', { class: 'carousel'}, [
    h('p', `My default slot has ${slots.default().length} elements.`),
    h('div', slots.default()[index.value]),
    h('p', `Picture ${ index.value + 1 }`),
    h('button', { onClick: () => { 
      index.value = index.value + 1 == slots.default().length ? 0 : index.value + 1
    } }, 'Next')
  ]);
};
</script>

<template>
    <render />
</template>

Check out the working SFC Playground

Using the default slot and avoiding a render function seems to be the only way to achieve what you want.

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

Increase the loading speed of the tooltip when hovering over the Legend of the Doughnut chart

I have a similar implementation to the answer provided in this response, which I will share here for better understanding. When you hover between items in the legend and do so quickly, you may notice that the tooltip on the chart does not always display. ...

Use ajax request to serialize input into HTML value

I implemented a jquery.ajax post request to send data to the server using C#, however, I encountered an error with my code. Here is the code snippet: $(function(){ $('#frmSubmit').on('submit', function(e){ e.preventDefault(); ...

Launch an Android application directly from a web browser upon the webpage's loading

When a user visits www.example.com/myApp, I want my app to open automatically without any click required. I have attempted the following methods: window.onload = function () { window.location.replace("intent://something#Intent;scheme=myapp;packag ...

Error: Attempting to assign a value to a property of #<Object> that is read-only

I'm working on a task management application and encountering an issue when trying to assign an array of tasks stored in localStorage to an array named todayTasks. The error message being thrown is causing some disruption. https://i.sstatic.net/uFKWR. ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...

Sort the array of objects based on the nested attribute

I am facing a challenge in ordering an array based on a nested object. The array contains information about objects on a timeline and I would like to sort it by the start position defined within nested arrays. Currently, I am able to iterate through the ar ...

Linking Vue.js drop-down menus to Ruby on Rails

I've encountered a challenge while building a Vue.js form with select boxes. Despite successfully posting the data to my Rails app, I face an issue when editing the object later on. The pre-selected values in the select boxes do not match what was ori ...

Creating a Kendo Menu within an Ext JS Panel

Currently, I am experimenting with combining ExtJS and Kendo UI - a unique mix that is taking me off the usual path ;) I have managed to render a Kendo Menu onto an Ext JS (4.2.1) generated Ext.form.Panel In case you want to check it out, here's a F ...

How to retrieve email input using SweetAlert2 in PHP?

Hello there! I'm curious about the most effective method for integrating PHP with Javascript. My goal is to execute some coding tasks once an email address has been entered. swal({ type: "success", title: "Congrats!", text: "Please enter your P ...

How can I create distinct edges that intersect the surfaces of other objects in THREE.js?

Currently, I'm involved in a three.js project where I need to display all edges of geometries, even when those edges intersect with surfaces of other objects. Below is the code snippet that showcases my dilemma: var camera, scene, renderer, materi ...

Parsing temporary storage of database query results

My experience with OOP languages like C# and Java has been good, but I am relatively new to JavaScript/TypeScript. I find callback functions confusing, especially when using them with the BaaS ParseDB. For example, finding all playlists for a certain user ...

Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one. The function I need to call is popup() random() = 'popup()' if ($.cookie('optin-page')) { } I attemp ...

Creating an HTTP request in Node.js and saving it to a file

Is there a way for me to save HTTP requests onto a file? My server is using Node.js. I am sending data via AJAX as shown below: user_info = { system_info: [ {'browesr': browser}, {'brower-version': ...

Add a jQuery script to the admin panel of a custom WordPress plugin for sending emails through ajax

I've been working on integrating a form into an admin page on WordPress. The goal is to allow users to input their email address and trigger an email to be sent to that address. To achieve this, I'm utilizing a jQuery Ajax function to transmit th ...

Accessing a model's field within an Ember.js each loop

Here is the code for a route that I am working on: Calendar.DateIndexRoute = Ember.Route.extend({ model: function(data) { return {arr:getCalendar(data), activeYear: data.year, activeMonthNumber: data.month, activeDay: data.da ...

Using node.js and express framework to manage additional .get requests

At the moment, I have implemented the following code: app.get('/prices/all', function (req, res) { fs.readFile( __dirname + "/" + "data.json", 'utf8', function (err, data) { res.set({ 'content-type': 'applicat ...

Show data in a popup using jQuery DataTables and loading content asynchronously via Ajax

I am attempting to display a list in a popup based on an Ajax request. Prior to the Ajax call, the list is contained within the popup. However, after the Ajax request, the list remains on the page instead of inside the popup, and the old list still appears ...

Navigating between various arrays

I'm struggling to create a basic slideshow using the JavaScript code below, but it doesn't seem to be functioning correctly. I have meticulously checked for any errors in spelling and made sure all elements are correctly linked to my HTML. JavaS ...

Guide on updating location and reloading page in AngularJS

I have a special function: $scope.insert = function(){ var info = { 'username' : $scope.username, 'password' : $scope.password, 'full_name' : $scope.full_name } $http({ method: &ap ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...