vue / typescript / vue-awesome-swiper 中的`this`方向

`this` direction in vue / typescript / vue-awesome-swiper

代码


export default class Random extends Vue {
  // data
  public nowIndex: number = -1;
  public swiperOption: Object = {
    slidesPerView: 6,
    slidesPerGroup: 6,
    loopFillGroupWithBlank: true,
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev"
    },
    on: {
      click: function(this: any): void {
        nowIndex = this.clickedSlide.dataset.key;
      }
    }
  };
}

问题: 单击事件的 this 直接指向 Swiper 元素,我需要它得到一个键来告诉我哪个被点击了,我想把这个键保存在 vue 数据 ---- nowIndex 中,但是我有一个错误说 "Cannot find name 'nowIndex'"

我的工作: 我尝试在 class 中定义一个 public 值 vue 直接到 this,但它不起作用,错误还显示 "Cannot find name 'vue'"

结束: 希望有人能看到,给我一条出路,觉得你很TAT。

nowIndex = 是一个错误,因为没有 nowIndex 变量,并且 nowIndex class 属性 应该始终称为 this.nowIndex

The documentation 状态:

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

正如 this answer 所解释的,这是库中的设计问题,它依赖于回调中的 this;一个函数不能同时使用组件 this 和 swiper this 上下文。这可以通过使用 self = this hack 或通过将函数签名绑定到这些上下文之一并使其接受另一个作为参数来解决。

这可以通过 中建议的辅助函数来完成:

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;
        })
      }
    };
  }
}

或者通过使用 hack,在这种情况下 this 语义出错:

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;
        })
      }
    };
  }
}