Search code examples
methodsvue.jscomponents

Why won't VueJS invoke methods from the created() function?


Learning VueJS and trying to do a simple API call on component load to put a list of repos onto my page. When I call and set the this.repos from the created() method, no problem. But if I set it as a method and then call it from this.getRepos nothing happens. No error, nothing. What am I missing about VueJS?

This works:

data: () => ({
    msg: 'Github Repos',
    ok: 'Im practically giving away these repos',
    repos: [],
  }),
  methods: {
  },
  async created() {
    const repos = await axios.get('https://api.github.com/orgs/octokit/repos');
    this.repos = repos.data.map(repo =>
      `<div class="box"><a href="${repo.html_url}">
        ${repo.name}
      </div>`,
    );
  },

This DOES NOT work:

data: () => ({
    msg: 'Github Repos',
    ok: 'Im practically giving away these repos',
    repos: [],
  }),
  methods: {
    getRepos: async () => {
      const repos = await axios.get('https://api.github.com/orgs/octokit/repos');
      this.repos = repos.data.map(repo =>
        `<div class="box"><a href="${repo.html_url}">
          ${repo.name}
        </div>`,
      );
    },
  },
  created() {
    this.getRepos();
  },

Any ideas? Thanks!


Solution

  • It's simply because you used arrow functions here so that this.repos's this is bound to window object. Changing async () => {} to async function() {} will help you overcome it.

    See demo

    Note that you should not use an arrow function to define a method (e.g. plus: () => this.a++). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.a will be undefined.

    reference