使用Vue方法时,访问数据时无法使用“ this”

时间:2018-10-22 09:36:20

标签: javascript vue.js

这是我的代码:

let app = new Vue({
    el: '#app',
    data: {
        groups: [],
    },

    methods: {
        loadGroups(){
            axios.get('/api/groups')
                .then(function (response) {
                    // handle success
                    app.groups = response.data; //The important line
                });
        },
        addGroup(){
            this.loadGroups();
            console.log(1);
        }
    },

loadGroups方法中,我使用的是app.groups = response.data;,它可以正常工作,但是我宁愿使用this.groups = response.data;或类似的方法,但是我不能这样做,因为this所指到窗口,而不是Vue实例。我该怎么做才能显得更友好?

1 个答案:

答案 0 :(得分:4)

以下是三种方法,其中最先进的是第一种:

loadGroups(){
    axios.get('/api/groups')
        .then(response => {   // for arrow functions `this` is just another variable
            // handle success
            this.groups = response.data;
        });
}

loadGroups(){
    axios.get('/api/groups')
        .then(function (response) {
            // handle success
            this.groups = response.data;
        }.bind(this));     // binding `this` to the function makes it keep `this`
}

loadGroups(){
    var that = this;        // old style approach with a proxy variable
    axios.get('/api/groups')
        .then(function (response) {
            // handle success
            that.groups = response.data;
        });
}

this丢失的原因是未将回调作为方法调用。当使用function关键字(不是箭头)定义函数并且您从对象的属性(即某处有一个点-或至少是方括号)中调用该函数时,就会发生方法调用。该对象称为“接收者”,并分配给this

const obj = {
  not_method: x => x * 2,
  method: function(x) { return x*2; }
}
obj.not_method()    // not a method call (arrow); `this` is unaffected
f = obj.method; f() // not a method call (not property); `this` is `global` or `window`
obj.method()        // method call; `this` is `obj`
obj['method']()     // still a method call; `this` is obj

axios.get不在乎this;它接收一个参数,例如称为callback,并将其命名为:callback(response);由于callback中没有点或方括号,因此它不是方法调用,并且this是全局范围。

第一段代码将功能更改为箭头功能。根据其定义,箭头函数完全忽略this,将其视为任何其他变量。因此,this将被函数关闭,您可以从闭包中获取其在闭包外部的值。

第二段代码使用Function.prototype.bind强制一个函数将this分配给我们选择的值。它也可以填充一些参数,但是我们并没有使用它,只是接收器。

在箭头函数成为事物之前,第三段代码模拟了第一段代码。我们将this的值分配给另一个变量,该变量不是this这样的魔术,因此将通过常规机制在闭包中捕获。