[Vuejs]-Automatically Sliding Carousel

2๐Ÿ‘

โœ…

You could use setInterval() to call next() function. After that you should add a beforeDestroy() method to clear the interval.
You can also add a button to to start/stop the interval with the same code.

Example to start auto-slide on page mounted()

mounted(){
        ....
        this.interval = setInterval(() => { this.next() }, 5000)
},
beforeDestroy () {
        clearInterval(this.interval)
}

๐Ÿ‘คAbregre

1๐Ÿ‘

I think we should have a method that do this with a setInterval stored so we can clear it when we call next or prev

data() {
  return {
    ...
    interval: null,
  }
},

methods: {
  switchInterval() {
    // if it's already set we clear so we reset calculation
    if (this.interval !== null) clearinterval(this.interval);
    this.interval = setInterval(() => {
       // call next or prev logic
    }, 5000)
  },

  next() {
     ...
     // you can use the same logic in prev()
     this.switchInterval()
  },
  ...
},

beforeDestroy() { 
 // just make sure this.interval is not null
 if (this.interval) clearInterval(this.interval)
}

๐Ÿ‘คkhofaai

Leave a comment