Getting Started with Vue.js

Vue Lifecycle Events

When building our Vue apps, Vue does a great job at binding data, making our views reactive, and handling updating everything. This whole process of Vue creating all the reactivity is called the lifecycle.

There may be instances where we need to hook into the lifecycle so that we can run our own processes. A main reason for hooking into Vue's lifecycle is to grab data when the Vue app is created.

We can grab HTTP requests from inside Vue's lifecycle events.

Lifecycle Hooks

Vue has certain lifecycle events that we can hook into to run our code. The main ones are:

  • created
  • mounted
  • updated
  • destroyed

We also have access to these other hooks that run before the above:

  • beforeCreate
  • beforeMount
  • beforeUpdate
  • beforeDestroy

Here's Vue's diagram to show off the life of a Vue instance:

Getting Data on Vue Startup

Let's say we wanted to grab a list of users from an external API when a user lands in our app. We will want to use the created lifecycle hook.

Here we have our data and methods to start showing our users. Where should we use that getUsers function when a user lands on our page?

const app = new Vue({
  el: '#app',

  data: {
    users: null // create the variable so Vue knows it exists
  },

  methods: {
    getUsers: function() {
    // go get the users using an HTTP call
    // fetch('http://my-api-url.com').then(data => this.users = data);
    }
  }
});

Once we have run the HTTP call, we can bind the data that comes back to our users data variable. This is psuedo code for a quick example on making an HTTP call with fetch.

Using Lifecycle Hooks

To use the lifecycle hooks, add another method to our Vue instance with the name of the hook. Let's add a created hook and also use the getUsers function there.

const app = new Vue({
  el: '#app',

  data: {
    users: null // create the variable so Vue knows it exists
  },

  methods: {
    getUsers: function() {
      // go get the users using an HTTP call
      // fetch('http://my-api-url.com').then(data => this.users = data);
    }
  },

  // when our Vue app is created, go get the list of users
  created: function() {
    this.getUsers();
  }
});

Now we have an exact place to look for activities when we want to know what our Vue app is doing on creation!