[Vuejs]-`this` direction in vue / typescript / vue-awesome-swiper

0👍

nowIndex = is a mistake because there’s no nowIndex variable, and nowIndex class property should always be referred as this.nowIndex.

The documentation states:

Please note, that this keyword within event handler always points to Swiper instance

As this answer explains, this is design problem in a library that relies on this in callbacks; a function cannot use component this and swiper this contexts at the same time. This can be solved either by using self = this hack, or by binding function signature to one of these contexts and making it accept another one as a parameter.

This can be done with helper function as suggested in this answer:

function contextWrapper(fn) {
    const self = this;

    return function (...args) {
        return fn.call(self, this, ...args);
    }
}

export default class Random extends Vue {
  nowIndex: number = -1;
  swiperOption?: any;

  created() {
    this.swiperOption = { /*...*/
      on: {
        click: contextWrapper((swiperInstance: any) => {
          this.nowIndex = swiperInstance.clickedSlide.dataset.key;
        })
      }
    };
  }
}

Or by using a hack, in this case this semantics goes wrong:

export default class Random extends Vue {
  nowIndex: number = -1;
  swiperOption?: any;

  created() {
    const self = this;

    this.swiperOption = { /*...*/
      on: {
        click(this: any) {
          self.nowIndex = this.clickedSlide.dataset.key;
        })
      }
    };
  }
}

Leave a comment