Summer Sale! All accounts are 50% off this week.

Gabotronix's avatar

Vue: issue with setInterval function inside component methods

Hi everybody, I'm making progress on my custom slider component, I can get setInterval to execute a method each X seconds, issue is Im getting the following error:

TypeError: this.nextSlider is not a function

This is my component logic:

<script>
export default {
name: 'MainSlider',

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    this.startSlider();
},

props: {
    slidercount: {required:true, type: Number},
    sliderinterval: {default: 5000, type: Number},
},

data() {
    return {
        sliderTimer: 0,
        activeslider: 1,
    }
},

methods:{


    startSlider() {
        
        this.sliderTimer = setInterval(function(){
        this.nextSlider() }, 5000);
    },


    prevSlider() {
        if(this.activeslider == 1){
            this.activeslider = this.slidercount;
        }
        else{
            this.activeslider = this.activeslider - 1;
        }
    },


    nextSlider() {
        if(this.activeslider == this.slidercount){
            this.activeslider = 1;
        }
        else{
            this.activeslider = this.activeslider + 1;
        }
    },


    goToSlider (sliderIndex) {
        this.activeslider = sliderIndex;
        clearInterval(this.sliderTimer);
        
    },

}
};
</script>
0 likes
1 reply
realrandyallen's avatar

this is referring to the closure you’re inside of, where that method doesn’t exist - try this:

startSlider() {
     let self = this;

     this.sliderTimer = setInterval(function(){
          self.nextSlider();
     }, 5000);
},

Please or to participate in this conversation.