簡體   English   中英

如何更改調用Vue實例方法的`this`上下文?

[英]How to change `this` context calling Vue instance methods?

.callFunction.prototype.apply.bind方法不適用於在.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 })();
    }

控制台的預期 output 是三重{ bar: 42 } ,因為this調用的值已更改。 但是, VueComponent object 會打印到控制台。

我檢查了這些方法的重載,使用this.foo.bind === Function.prototype.bind // returns true ,它們沒有重載。

這可能是 Vue 使用Proxy對象甚至模板編譯造成的。

上面代碼的最簡單的@vue/cli項目足以重現問題。

謝謝

Vue 組件方法綁定到上下文,即組件實例。 這可以通過以下方式檢查:

function foo() {
    foo() {
        console.log(this);
    }

}

...
methods: { foo },
created() {
    this.foo !== foo // true
}
...

this.foo.bind === Function.prototype.bind檢查不具有代表性,因為this.foo是常規的 function,因此它繼承了bind

一旦 function 被綁定,它就不能被重新綁定或被不同的上下文調用:

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

在 JS OOP this依賴任意動態上下文不是一個好習慣。 如果一個方法需要一個上下文,它應該作為一個參數提供給它:

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

或作為實例屬性共享,具體取決於用途。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM