Home > Software design >  Vue how to trigger click on links based on interval
Vue how to trigger click on links based on interval

Time:10-28

In my vue-app I have a list of links, which I want to be triggered automatically one by one by a default interval, lets say after 3 seconds, the first link gets triggered, then after another 3 seconds, link 2 gets triggered... so its kind of a carousel/autoplay with links I want to achieve, but I don't really know how to solve that.

here is my code:

<li v-for="(slide, index) in slides" :key="index" :class="slideIndex === index ? 'active' : ''" @click="slideIndex = index" ref="slide">
 {{ slide.title }}
</li>

and then I thought somethinbg like this:

mounted() {    
  Object.keys(this.$refs.slide).forEach((el) => {
    setInterval(() => {
      this.$refs.slide[el].click();
    }, 3000);
  });
},

but this triggers all links and does not seem to be right at all, but its just a slight idea...

Can someone help me out?

CodePudding user response:

I would not recommend doing this by simulating a click on the link.

How about setting the element you want to be active in your code?

I assume slideIndex is the current selected slide?

You could try something like this:

setInterval(() => {
    this.slideIndex = this.slideIndex < this.slides.length - 1 ? (this.slideIndex  = 1) : 0;
}, 3000);

So you add 1 every time the interval is triggered and cycle through the slides. If it's at the end slideIndex gets reset and starts at 00

  • Related