Sol
Sol

Reputation: 11

How do you call methods in vue3-carousel

Very new to using vue, I just got simple question on how I could access the API supplied by vue3-carousel according to the docs: https://ismail9k.github.io/vue3-carousel/getting-started.html

Under the API section there are a few methods supplied with the library for example I would like to use the: slideTo(index: number) method that the documentation supplied to start the carousel on second item instead of the defaulted first item.

Upvotes: 1

Views: 2995

Answers (3)

Ross Adriano
Ross Adriano

Reputation: 25

To call methods on a component, assign a ref and call the method any time on or after the mounted lifecycle hook.

<template>
    <Carousel ref="carousel"></Carousel>
</template>
// Get the carousel ref
const calendar = this.$refs.carousel

// call the method
carousel.slideTo(3)

Upvotes: 0

Lan
Lan

Reputation: 1

Instead of

const slideToBeginning = () => myCarousel.slideTo(0);

It should be

const slideToBeginning = () => myCarousel.value.slideTo(0);

Upvotes: 0

maembe
maembe

Reputation: 1300

internally, vue3-carousel uses the expose method in the composition api, which exposes properties/methods on the component instance via template refs.

<template>
   <div>
         <Carousel ref="myCarousel"></Carousel>
         <button type="button" @click="slideToBeginning">to beginning</button>
   </div>
</template>

<script>  

import { ref } from 'vue'

export default {
   setup() {
      //the name of the variable is equal to the ref value of the carousel component
      const myCarousel = ref(null);  

      // now we can use myCarsousel's exposed methods
      const slideToBeginning = () => myCarousel.slideTo(0);

      return {
          myCarousel,
          slideToBeginning 
      }
   }

</script>

Upvotes: 2

Related Questions