Vue watch[fat arrow scope] 提供了错误的 this 上下文

Vue watch[fat arrow scope] providing wrong this context

我正在使用 lodash 来消除函数调用的抖动,但我想知道为什么我的 this 值没有像我期望的那样继承作用域。

这些是我的 Vue 组件的相关部分。

import debounce from 'lodash/debounce';

watch: {
    query: debounce(() => {
        this.autocomplete();
    }, 200, {
        leading: false,
        trailing: true
    }),

上述情况不起作用,因为我的 this 值不指向 Vue 组件,而是显示一个像这样的对象:

Object
    __esModule: true
    default: Object
    __proto: Object

我的箭头语法不是应该继承 this 的上下文吗?

以下似乎工作正常:

query: debounce(function test() {
    this.autocomplete();
}, 200, {
    leading: false,
    trailing: true
})

这个问题可能有一个简单的答案,但我希望有人能帮助我。

https://vuejs.org/v2/guide/instance.html#Properties-and-Methods

Don’t use arrow functions on an instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.

由于同样的限制适用于观察者,你必须使用这样的东西:

watch: {
    query: function() {
        return debounce(() => {
            this.autocomplete();
        },
        200,
        {
            leading: false,
            trailing: true
        });
   }
}

这只是为了解释箭头函数中对this的误解的补充回答

这在箭头函数中是如何工作的?

this 在词法函数中总是指周围的范围。这可以是:

  1. 最近的周围函数
  2. 最近的周边模块
  3. 全局范围

如果我们查看您的代码,我们假设您使用的是 ES6 模块(根据 import/export 语句判断):

import debounce from 'lodash/debounce';

export default {
    watch: {
        query: debounce(() => {
            this.autocomplete();
        }, 200, {
            leading: false,
            trailing: true
        }),
    }
};

让我们浏览一下列表:

1.最近周围函数

你的箭头函数没有环绕函数。一个例子是:

var obj = {
    a: function() {
        return () => {
            console.log(this);
        }
    }
};

obj.a()(); // `this` refers to `obj`, because `this` refers to `obj` in the surrounding function `a`

2。最近的周围模块

由于我们在这种情况下处于(假)模块中,this 在模块范围内被定义为伪模块对象(可能是 babel 或 webpack 对象?)。

Object
    __esModule: true
    default: Object
    __proto: Object

好像是因为Vue默认绑定了这些属性、方法和事件

没错,这是 vue 的一个非常有用的功能。但在这种情况下它对我们没有帮助,因为 this 不能在箭头函数中被覆盖,它总是引用周围的范围 .

查看以下内容link 以更深入地了解箭头函数:http://exploringjs.com/es6/ch_arrow-functions.html#_variables-that-are-lexical-in-arrow-functions