People keep showing me the same way to create a carousel using an array of images. But this approach is inflexible because I want each slide of the carousel to contain a lightbox component. In this case I don't want to override the functionality of the lightbox for the images I put into the carousel array. Isn't that great? Write less code and make reusable components in Vue.js more useful than ever.
I found a very good example of using slots. Vue Carousel by SSENSE on GitHub. As a not very proficient web developer, I still don't understand how he got each slide to display a slot. This is a template
<carousel :per-page="1" :navigate-to="someLocalProperty" :mouse-drag="false"> <slide> Slide 1 Content </slide> <slide> Slide 2 Content </slide> </carousel>
As you can see, we have a parent component carousel and child component slideshow. The hardest part for me was figuring out how to extract some data from it, like index, amount, etc., to create the functionality of the carousel. I agree that it is much simpler to create a carousel with an array of images, but this approach does not allow us to use another component within the carousel.
What do I want? I want to somehow extract the index of each slot that slides in this case and then I can easily create a function for the carousel by changing the index. I think there are different paths to creating carousels with slots, but I still don't quite understand all the concepts of Vue and JavaScript, so can you tell me different ways to solve this problem.
P粉4028061752024-01-11 12:39:29
You can access slot elements in a component using the slots
parameter of the setup
function (also used with the useSlots()
component, which is equivalent to this.$slots
in the options API).
Then you can know how many elements it contains.
<script setup> const slots = useSlots() onMounted(() => { const defaultSlotElements = slots.default() console.log(`My default slot has ${defaultSlotsElements.length} elements.`) }) </script>