DEV Community

Valentina Peric
Valentina Peric

Posted on

The Heart of all Vue.js Applications: Vue Instance

Let's talk about the heart of all Vue.js applications. The motherboard. The part that is absolutely essential to running these applications: Vue Instance. What is it? How do we use it? In this article, I will help break down what this fundamental topic is and how they are used in Vue applications.

Prerequisites đź“ť

  1. A working knowledge of javascript
  2. A code editor (I recommend Visual Studio Code)
  3. A working knowledge of Vue.js (V2)

Let's Get Started ✨

Please note: This is in Vue.js V2. You will see in V3, the initialization is a bit different. You can read more about it here. Back to our scheduled programming 👇,

To put it simply, the Vue Instance is the root of every Vue application. It is used to connect the data, properties, and lifestyle hooks. Let's take a look at an example and go from there,

new Vue({
  el: '#app',
  data: {
    books: Seed.books
  },
  created: function () {
    console.log('hello world')
  }
});
Enter fullscreen mode Exit fullscreen mode

When a Vue instance is created, an options object is passed in. In the example above, this object contains the el and data property. el represents a specific part of the DOM that the Vue instance will be mounted to, which in this case, is the #app. Typically, you will see that #app is the root of application.

The second property is data. This property passes in an object that contains reactive data. Any changes to that data will cause a rerender of its corresponding view in the DOM. This happens because of vue's reactivity system which consists of two-way databinding.

In the example above, you will see that books was passed in. This could be an array of objects holding data about books. If this app was a library system and a librarian added a book to the system, this array would be updated which would cause the #app view to rerender. This creates a seamless user experience.

The Vue instance also provides a set of lifestyle hooks. These hooks help with tasks like initialization and clean-up. Common hooks are created, mounted, updated, and destroyed. The above example shows the created hook. This means that its function will get called when the Vue instance is created which in this case, hello world will get printed out in the console.

Next Steps ✨

So there you have it, the heart of all Vue applications. Do not forget to add this instance to your Vue app (I have! It will cause errors hehe) and you will see how it essential it is for building your app. Take a look at Vue projects or build your own to see it in action.

Top comments (0)