ajax – beforeCreate hook中的Vue 2.1调用方法不起作用

前端之家收集整理的这篇文章主要介绍了ajax – beforeCreate hook中的Vue 2.1调用方法不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在创建组件之前,我正在对一些本地json数据进行异步调用.所以这段代码实际上工作正常:
  1. beforeCreate : function() {
  2. var self = this;
  3. fetch('/assets/data/radfaces.json')
  4. .then(function(response) { return response.json()
  5. .then( function(data) { self.users = data; } );
  6. })
  7. .catch(function(error) {
  8. console.log(error);
  9. });
  10. },

现在我只想重构并将其移动到一个单独的方法

  1. beforeCreate : function() {
  2. this.fetchUsers();
  3. },methods: {
  4. fetchUsers: function() {
  5. var self = this;
  6. fetch('/assets/data/radfaces.json')
  7. .then(function(response) { return response.json()
  8. .then( function(data) { self.users = data; } );
  9. })
  10. .catch(function(error) {
  11. console.log(error);
  12. });
  13. }
  14. }

现在一切都停止了.我收到一个错误:app.js:13 Uncaught TypeError:this.fetchUsers不是函数(…)

为什么我不能访问beforeCreate钩子中的fetchUsers方法?有什么工作?

这是因为方法尚未初始化.最简单的方法是使用创建的钩子:
  1. created : function() {
  2. this.fetchUsers();
  3. },methods: {
  4. fetchUsers: function() {
  5. var self = this;
  6. fetch('/assets/data/radfaces.json')
  7. .then(function(response) { return response.json()
  8. .then( function(data) { self.users = data; } );
  9. })
  10. .catch(function(error) {
  11. console.log(error);
  12. });
  13. }
  14. }

猜你在找的Ajax相关文章