如何更改`this`上下文以调用Vue实例方法?

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

.call的[.apply.bindFunction.prototype方法不适用于曾经在.vue文件中定义为Vue实例的方法的功能。

我正在使用@vue/cli项目,并使用vue-cli-service serve进行编译。这是简化的代码示例,可以将其放在任何Vue单文件组件定义中。

    methods: {
        foo() {
            console.log(this);
        }
    },
    created() {
        this.foo.call({ bar: 42 });
        this.foo.apply({ bar: 42 });
        this.foo.bind({ bar: 42 })();
    }

预期到控制台的输出是三倍{ bar: 42 },因为这些调用的this值已更改。但是,VueComponent对象将打印到控制台。

我检查了这些方法的重载,使用this.foo.bind === Function.prototype.bind // returns true,他们没有超载。

[可能是由于Vue使用Proxy对象,甚至是模板编译引起的。

具有上面代码的最简单的@vue/cli项目将足以重现此问题。

谢谢

javascript vue.js this bind
1个回答
0
投票

Vue组件方法绑定到作为组件实例的上下文。

一旦绑定了一个函数,就不能重新绑定它,也不能在不同的上下文中调用它:

const context = {};
const boundFoo = (function foo() { return this; }).bind(context);
// boundFoo.call({}) === context

在JS OOP中依赖于任意动态this上下文不是一个好习惯。如果方法需要上下文,则应将其作为参数提供给它:

methods: {
    foo(ctx) {
        console.log(ctx);
    }
},
created() {
    this.foo({ bar: 42 });
}

或根据目的共享为实例属性。

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