Search code examples
vue.jsowl-carousel

Vue JS: owl carousel item.index unable to update data


I'm facing an issue where the events happening in the owl carousel does not update data values outside of the function

This is my code:

endScenario: function() {
                $(".owl-carousel").on('changed.owl.carousel', function(e) {
                    this.carouselIndex =  e.item.index;
                    var numCarouselItems = $('.carousel__item').length - 1;


                    if (numCarouselItems === this.carouselIndex) {
                        this.isEndingActive = true
                    }
                    

                    console.log(this.carouselIndex)
                    console.log(this.numCarouselItems)
                    console.log("this is inside the owl function : " + this.isEndingActive) 
                });
                console.log("this is outside the owl function : " + this.isEndingActive)
            }
data: {
      isEndingActive: false,
}

The user is supposed to scroll through the carousel and when the user is at the final slide of the carousel, it will trigger the endScenario function which suppose to update the isEndingActive: false -> true but when the requirement is fulfil, it does not trigger the change from false to true. Is there a reason why and how do I rectify this?

enter image description here


Solution

  • it seems the usage of this
    the outside this is not equal the inside this
    you can resolve it by arrow function

     $(".owl-carousel").on('changed.owl.carousel', e => {}
    

    or you can save a variable

    endScenario: function() {
      const self = this;
      $(".owl-carousel").on('changed.owl.carousel', function(e){
         //use self replace this
      });
    }