2016-11-30 13 views
7

मैं अपने घटक बनने से पहले कुछ स्थानीय json डेटा पर एसिंक कॉल कर रहा हूं। तो यह कोड वास्तव में ठीक काम करता है:पहले से बना 2.1 कॉलिंग विधि क्रेट हुक काम नहीं कर रहा है

beforeCreate : function() { 
    this.fetchUsers(); 
    }, 

    methods: { 
    fetchUsers: function() { 
     var self = this; 
     fetch('/assets/data/radfaces.json') 
     .then(function(response) { return response.json() 
     .then(function(data) { self.users = data; }); 
     }) 
     .catch(function(error) { 
     console.log(error); 
     }); 
    } 
    } 

और अब सब कुछ कार्य करना बंद कर:

beforeCreate : function() { 
    var self = this; 
     fetch('/assets/data/radfaces.json') 
     .then(function(response) { return response.json() 
     .then(function(data) { self.users = data; }); 
     }) 
     .catch(function(error) { 
     console.log(error); 
     }); 
    }, 

अब मैं सिर्फ refactor और एक अलग विधि को यह ले जाना चाहते हैं। मुझे एक त्रुटि मिलती है: app.js:13 Uncaught TypeError: this.fetchUsers is not a function(…)

मैं beforeCreate हुक में fetchUsers विधि का उपयोग क्यों नहीं कर सकता? चारों ओर काम क्या है?

उत्तर

11

ऐसा इसलिए है क्योंकि methods अभी तक प्रारंभ नहीं किया गया है। इसके बजाय created हुक का उपयोग करने के लिए सबसे आसान तरीका:

created : function() { 
    this.fetchUsers(); 
    }, 

    methods: { 
    fetchUsers: function() { 
     var self = this; 
     fetch('/assets/data/radfaces.json') 
     .then(function(response) { return response.json() 
     .then(function(data) { self.users = data; }); 
     }) 
     .catch(function(error) { 
     console.log(error); 
     }); 
    } 
    } 
+0

क्या आप जानते हैं कि दस्तावेज़ में मैं कहां पढ़ सकता हूं? –

+1

हां, आप यहां और अधिक जानकारी प्राप्त कर सकते हैं: https://vuejs.org/v2/api/#Options- लाइफसाइकिल- हुक –

संबंधित मुद्दे