在创建组件之前,我正在对一些本地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);
- });
- }
- }