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

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(…)

为什么我不能fetchUsersbeforeCreate钩子中访问该方法?有什么工作?

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)

  • 是的,您可以在此处了解更多信息:https://vuejs.org/v2/api/#Options-Lifecycle-Hooks (2认同)