Ami*_*ole 10 ajax hook lifecycle asynchronous vue.js
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);
});
},
Run Code Online (Sandbox Code Playgroud)
现在我只想重构并将其移动到一个单独的方法:
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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在一切都停止了.我收到一个错误:app.js:13 Uncaught TypeError: this.fetchUsers is not a function(…)
为什么我不能fetchUsers在beforeCreate钩子中访问该方法?有什么工作?
cra*_*g_h 18
这是因为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);
});
}
}
Run Code Online (Sandbox Code Playgroud)