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

时间:2023-01-26 09:07:02

I am making an async call to some local json data before my component is created. So this code actually works fine:

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

Now I just want to refactor and move this to a separate method:

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

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

And now everything stops working. I get an error: app.js:13 Uncaught TypeError: this.fetchUsers is not a function(…)

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

Why can't I access the fetchUsers method in the beforeCreate hook? What is the work around?

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

1 个解决方案

#1


11  

It's because methods hasn't been initialized yet. The easiest way around this it to use the created hook instead:

这是因为方法尚未初始化。最简单的方法就是使用创建的钩子:

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

#1


11  

It's because methods hasn't been initialized yet. The easiest way around this it to use the created hook instead:

这是因为方法尚未初始化。最简单的方法就是使用创建的钩子:

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