vue3-carousel
vue3-carousel copied to clipboard
The initial currentSlideIndex isn't accurate
Describe the bug
I'm trying to track the current slide index using the following snippet:
<Carousel @update:modelValue="value => currentSlide = value">
...
However, it doesn't get a value until the slide changes (aka it doesn't set the initial value upon init).
To Reproduce
Steps to reproduce the behavior:
- Use an event listener to set a local
ref(). - When the component mounts, the value is whatever my initial value was from the
ref. - Change slides.
- The value is not updated to the correct index
Expected behavior
When the component mounts, it should emit the calculated first slide index. Is there another way to get the current index?
I believe that is because the model value itself isnt being updated on initial render. I.e. it is still 0
If you bind your currentSlide ref to the carousel like this <Carousel v-model="currentSlide">, the binding of the current slide will work, if your currentSlide starts = 0.
That last part is actually why I am here.. I too am experiencing an issue with the currentSlideIndex on initial load. It seems as though setting a default value other than 0 will be overridden by the default config modelValue (= 0). So in your example, if your initial currentSlide local ref starts as 0, my above suggestion should work. If you are trying to default to a slide that isnt the first slide (index=0), you will experience the same bug that I believe I am experiencing -- at least I think so..
So my workaround is adding a ref to the Carousel component, and doing this in setup()...
// <Carousel ref="carousel" ... />
const carousel = ref()
onMounted(() => {
nextTick(() => {
carousel.value.prev()
})
})
You could probably do this instead to solve your issue:
onMounted(() => {
nextTick(() => {
carousel.value.slideTo(yourDesiredIndex)
})
})
Fixed in the latest version