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

问题描述 投票:0回答:1

代码


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

问题:Click事件的this直接指向Swiper元素,我需要它来获取一个密钥来告诉我正在单击哪个密钥,并且我想将此密钥保存在vue数据中– nowIndex,但是我有一个错误提示“找不到名称'nowIndex'”

我做什么:我尝试在类中定义一个直接指向vue的公共值this,但它不起作用,错误还显示“ Cannot find name'vue'”

结束:我希望有人能看到这个并给我一个出路,非常想你TAT。

typescript vue.js swiper
1个回答
0
投票

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

The documentation状态:

请注意,事件处理程序中的此关键字始终指向Swiper实例

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

这可以通过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;
        })
      }
    };
  }

}

© www.soinside.com 2019 - 2024. All rights reserved.