Change array index to display next slide
P粉777458787
P粉777458787 2023-09-01 20:10:40
0
1
638
<p><pre class="brush:php;toolbar:false;"><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(`My default slot has ${defaultSlotElements.length} elements.`) }), onUpdated(() =>{ console.log(defaultSlotElements[index]) } ) </script></pre> <p>I'm trying to create a slot based carousel. Thanks to the previous guy on Stack Overflow who helped me figure out how to extract the slots array. Now, I'm dealing with another problem. In order to create the carousel, I have to somehow change the index of the elements in the array so that I can move to the next slide of the carousel. I later had to inject this into my slideshow component to have V-show render the current slot which defaults to 0. But the value of the index is changed by the v-on instruction that changes the index, so it selects the next or previous slot in the array. I know I've chosen a complex theme in vue, but I don't want to use a simpler version of a carousel based on an array of images, because I can't add another component in it. </p> <p>It turns out that I cannot select the next object in the array simply by changing the index <code>arr[index]</code>. </p>
P粉777458787
P粉777458787

reply all(1)
P粉155832941

If you really need to do this with slots, then you have to do this Using Vue rendering functions and 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>

This is workCSRC Playground

renew

Rendering functions can be used with custom components.

Here is an attempt to build your structure.

SFC Playground

I don't see any other way to use the default slot instead of using the render function to build what you want.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template