【问题标题】:`this` direction in vue / typescript / vue-awesome-swipervue / typescript / vue-awesome-swiper中的`this`方向
【发布时间】:2019-10-29 02:04:02
【问题描述】:

代码


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 ,但是我有一个错误说“找不到名称 'nowIndex'”

我做什么: 我尝试在类中直接定义了一个公共值vuethis,但它不起作用,错误还说“找不到名称'vue'”

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

【问题讨论】:

  • 我尝试在课堂上直接定义一个公共值 vue - 你是什么意思?

标签: typescript vue.js swiper


【解决方案1】:

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

The documentation 状态:

请注意,事件处理程序中的这个关键字总是指向 Swiper 实例

正如this answer 解释的那样,这是在回调中依赖this 的库中的设计问题;一个函数不能同时使用组件 this 和 swiper 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;
        })
      }
    };
  }
}

或者通过使用 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;
        })
      }
    };
  }
}

【讨论】:

  • 非常感谢您解决我的问题。我曾经在public vue = this 之类的课堂上尝试过第一个解决方案self = this,但它不起作用,你能教我这段代码在哪里以及如何工作吗?
  • 会使用suger语法,我差点忘了constructor,这是一个很大的错误,再次感谢:)
  • 很抱歉打扰你,我在编码时发现了另一个问题,bindAndPassContext 函数 bind 中的 this 直接指向类 Random 而不是 VueComponent ,所以如果我更新数据,视图未更新,我找不到将VueComponent this 放入此函数的方法
  • 您没有具体说明您是如何进行类继承的,但我想github.com/vuejs/vue-class-component 会如此。 Vue 类的问题在于它们并不是真正的 OOP,它们只是组件定义的语法。所以我之前关于constructor 的评论不相关。您需要在created 中执行此操作,这就是self = this 将发生的地方。我更新了帖子。
  • 很抱歉这个模糊的问题,答案是完美解决我的问题,但VueComponentRandom 之间的关系仍然让我感到困惑,@Component 装饰器是否在它们之间做了一些工作?
猜你喜欢
  • 2021-10-25
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2020-09-16
相关资源
最近更新 更多