ajax – beforeCreate hook中的Vue 2.1调用方法不起作用
发布时间:2020-12-16 01:36:39 所属栏目:百科 来源:网络整理
导读:在创建组件之前,我正在对一些本地json数据进行异步调用.所以这段代码实际上工作正常: beforeCreate : function() { var self = this; fetch('/assets/data/radfaces.json') .then(function(response) { return response.json() .then( function(data) { sel
在创建组件之前,我正在对一些本地json数据进行异步调用.所以这段代码实际上工作正常:
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不是函数(…) 为什么我不能访问beforeCreate钩子中的fetchUsers方法?有什么工作?
这是因为方法尚未初始化.最简单的方法是使用创建的钩子:
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); }); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |