代码之家  ›  专栏  ›  技术社区  ›  Tutu Kaeen

使用vue方法时,访问数据时不能使用“this”

  •  0
  • Tutu Kaeen  · 技术社区  · 7 年前

    这是我的代码:

    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 回复  |  直到 7 年前
        1
  •  4
  •   Amadan    7 年前

    以下是三种方法,最现代的方法是首先:

    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 关键字(不是箭头),然后从对象的属性调用它(即在某个地方有一个点-或至少是方括号)。对象被称为“receiver”,并被分配给 .

    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 不在乎 ;它接收一个参数,例如 callback ,并称之为: callback(response) ;因为在 回拨 ,这不是方法调用,而且 是全球范围。

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

    第二段代码使用 Function.prototype.bind 强制指定函数 以我们选择的价值。它也可以填充一些参数,但我们并不是用它来填充的,只是接收器。

    第三段代码模拟了第一段代码,在箭头函数成为一件事之前。我们将 到另一个变量,这不是魔术般的 ,因此将被正常机制捕获到闭包中。

    推荐文章