Introduction to Components in VueJS

Once you have learned the fundamentals of VueJS, It’s time to a step further and leverages the power of components.

Components, as their name suggests, encapsulates a part/feature of your page so that it becomes reusable. The functionality can be anything from a tiny button to a navbar to the whole page itself.

Consider the below code snippet. I have defined a Vue instance that mounts to the element with an id of app, and it does nothing.

    Vue.component('button-click-counter',{
        
    });


    var app = new Vue({
       el: '#app' 
    });

We have also defined a component named, which as the first argument accepts the name of the Component, button-click-counter in this case and as a second argument, it accepts an object of options. Since the component is the same as the Vue Instance it expects the same option objects as we pass to the Vue Instance.

Same as the Vue Instance, you might want to mount the component to an element, but components do not work like that. Since components are made to be reusable, you can define a markup structure in many ways. For the start let’s define the markup using a template string.


    Vue.component('button-click-counter',{
        template : '<button class="btn btn-primary" @click="count++">{{count}}</button>',

        data() {
            return {
                count: 0,
            }
        } 
    });

    var app = new Vue({
       el: '#app' 
    });

We have defined a custom template for our Component, which has a button and a click event listener.
We have also defined data methods that return the data object.

Note : data property defined in a Vue Instance is an object, where as in case of components it as an function that needs to return an object.

Here is the cool thing about components.

You can use them directly in your HTML as the custom element name.

As our component name is button-click-counter, we can use that in our HTML page.

    <div id="app">
          <button-click-counter></button-click-counter>
    </div>

When rendering the page, the component element will be replaced by the template string that we have provided and will also have the functionality defined. In this case, clicking the button should click the count.

Demo

Since components are reusable, you can use the element <button-click-counter> multiple times in your code, each button will maintain it’s state of the data.

Join my VueJS Newsletter

As I advance in my Journey of learning VueJS, I will be working on different exercises and challenges. Subscribe to receive the latest tutorials (every week) directly in your inbox.

    I won't send you spam. Unsubscribe at any time.

    Powered By ConvertKit

    Leave a reply:

    Your email address will not be published.

    Site Footer