2016-11-30 105 views
7

在创建组件之前,我正在对某些本地json数据进行异步调用。所以这段代码实际上正常工作:beforeCreate挂钩中的Vue 2.1调用方法不起作用

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); 
     }); 
    }, 

现在我只想重构和移动这一个单独的方法:

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); 
     }); 
    } 
    } 

而现在一切都停止工作。我收到一个错误: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-Lifecycle-Hooks –