2016-04-27 84 views
-2

我有一个组件在创建时请求数据。但是,当数据返回时,我无法访问直接父母范围内的任何内容。Vue.js丢失方法内部的范围

// Service 
class DataService { 
    getDataFromService() { 
    var p = new Promise(function(resolve, reject) { 
     resolve({ message: 'hello world' }); 
    }); 
    return p; 
    } 
} 
var dataService = new DataService(); 

// Component 
Vue.component('review', { 
    created: function() { 
    this.fetchData(); 
    }, 
    methods: { 
    fetchData: function() { 
     var that = this; 
     var hello = 'world'; 

     // normal function 
     dataService.getDataFromService().then(function(data) { 
     this.foo = data.message; // 'this' is undefined 
     that.bar = data.message; // 'that' is undefined 
     console.log(hello);  // 'hello' is undefined 
     }); 

     // fat arrow 
     dataService.getDataFromService().then((data) => { 
     this.foo = data.message; // 'this' is undefined 
     that.bar = data.message; // 'that' is undefined 
     console.log(hello);  // 'hello' is undefined 
     }); 
    }, 
    }, 
}); 

在上面的例子中,'this'和'that'都是未定义的,我不知道为什么。我使用babel & browserify编译代码。

我试着改变服务来使用回调,而不是承诺,没有改变任何东西。我也尝试使用正常的“功能(数据)”而不是胖箭头功能。

更新: 该示例适用于JSFiddle!我猜这意味着它与babel/browserify/modules有关。

+0

因为您可以访问ES6语法,所以如果不使用函数文字,可能会更容易一些。 – christopher

+0

我已经尝试过标准和胖箭头功能。两者都没有改变。我已经更新了这个问题以包含这些信息。 –

+0

'this'与非arrow函数中的''具有不同的值可能是可以理解的,但是'hello'未定义意味着您的环境中存在严重错误。这种行为在JavaScript中不被允许。 – Bergi

回答

-1

我最终切换到webpack停止了这个问题的发生。

0

使用箭头功能消除块作用域,以回调函数,你必须使用自=这个使用这个,而不是在箭头功能运行此脚本,看看怎么回事:

   var cb= function(f){ 
        f(); 
       } 


       var fetchData = function() { 
        var that = this; 
        this.data ='data'; 

        cb(() => { 
         console.log('---') 
         console.log(data); 
         console.log(that); 
        }); 
       }