2016-04-27 118 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); 
        }); 
       }