Vue Lifecycle Example

Vue.js is a JavaScript framework used to build the frontend of an application used by a couple of local freelance web designer singapore developers.

In this case study, we are going to look into the lifecycle of a Vue instance and understand what is going on beneath.

What is a Vue.js instance?

A Vue instance a concrete occurrence of a Vue object that exists during browser runtime. To configure a Vue instance, you will need to pass in an object that contains options that produces the desired behaviour of your application.
Basic structure of a lifecycle method

You cannot use the following es6 arrow syntax
Example of wrong structure

This will produce an error – this.increment is not a function

Why?- the arrow syntax causes “this” keyword to bind to the parent context which is usually the Window object of the browser.

Example of correct structure

“`
In this case, ‘this’ will refer to the Vue Instance instead of the window object in the previous case.

In this case study, we will ignore the other options but focus on lifecycle options.
The first lifecycle option is “beforeCreate”.

– [Vue.js](https://vuejs.org/v2/api/#beforeCreate)

– This method is called immediately after the Vue instance is initialised. Right before the processing of the options object.

Created – Vue instance has processed the entire Options object
At this stage, if there is a template rendered item in the browser. It will look like this {{ object }}. The data is not passed into the template yet.

beforeMount (Not called during SSR)

– Render function is about to be called for the first time. This is similar to React’s render function for those that come from React background.

– One thing to note, this is not called during server side rendering. If you are using Nuxt.js, do try this lifecycle method and see if it fails.

– {{ object }} will be replaced by the data specified in the data field during the process of this method
Mounted (Not called during SSR)

– called after instance has been mounted where el is replaced by the newly created vm.$el in the beforeMount method- use this.$nextTick if you want to run code when ALL child components are rendered.

beforeUpdate (Not called during SSR)

– when data changes when you call a method, this method runs before the Virtual Dom is re-rendered and patched with the latest updates.

– You are encouraged to do state changes in this hook because it does not trigger any additional rerenders.

– For example, if you change the currency of a website from USD to EUR this method is called and you might want to call the conversion method this.UsdToEur during this method

Updated (not called during SSR)

– this is called after the Virtual DOM is updated