beforeCreate 挂钩中的 Vue 2.1 调用方法不起作用

Vue 2.1 calling method in beforeCreate hook is not working

我在创建组件之前对某些本地 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 is not a function(…)

为什么我无法访问 beforeCreate 挂钩中的 fetchUsers 方法?解决方法是什么?

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