VueJS 错误“Uncaught TypeError: this.sendDrag is not a function” inmounted()

Tom*_*Tom 2 javascript vue.js vuejs2

我无法弄清楚为什么会this.sendDrag('started')返回此错误:

“未捕获的类型错误:this.sendDrag 不是函数”

  methods: {
    sendDrag (val) {
      console.log(val)
    }
[...]



    mounted () {
        this.$nextTick(() => {
          this.$refs.flickity.on('dragStart', function () {
            this.stageDragging = true
            this.sendDrag('started')
          })
Run Code Online (Sandbox Code Playgroud)

是什么导致错误以及如何修复它?

Ste*_*gin 6

您需要this在闭包中捕获 的值,因为您是从具有不同this.

如果您使用箭头-lambda 表示法()=>{}而不是function()它会this自动为您捕获。这就是两种符号之间的真正区别。

mounted () {
        this.$nextTick(() => {
          const that = this;
          this.$refs.flickity.on('dragStart', function () {
            that.stageDragging = true
            that.sendDrag('started')
          })

Run Code Online (Sandbox Code Playgroud)