Build Reusable Vue.js Components

    Greg ThomanGreg Thoman

    By building components, you can extend basic HTML elements and reuse encapsulated code. Most options that are passed into a Vue constructor can be passed into a component. Each instance of a component has an isolated scope. Data can only be passed one direction and it must be from parent to child using props. To communicate with the parent element, use the $emit method.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    00:00 Let's create a script tag with the type of x template and ID of dino counter. Because components are required to have a wrapper element, let's start with a div and put our button inside of it. The button text will be quantity, and we'll put the name of the dinosaur after it.

    00:16 After the data block in our main view component, let's create a components block. Our component, named dino counter, has an attribute of template that will set to reference our x template dino counter. After template, let's add a props array that will tell the component which properties to expect from the parent. These will be name and initial quantity.

    00:37 Let's add our data block. For components, data must be a function that returns the data the component is responsible for. In this case, we only need to return quantity, which we'll get from this.initial quantity.

    00:50 Let's add our new component to the parent. We'll get rid of this button and replace it with dino counter. Then let's bind the name to dino name and the initial quantity to dino quantity.

    01:03 Now we need to add a v on click to increment these values. On the dino counter component, let's add a methods block after data and add our increment function. It will take the current quantity and add one to it.

    01:17 What if we wanted a total of all the dinosaurs? On our parent component, let's add a methods block and add the function increment total. This function will accept an amount and add it to the total. Let's add a paragraph tag to our parent component to show total.

    01:32 We'll set up a custom event that will trigger from inside the dino counter component by setting v on increment to increment total. The child component is going to broadcast increment which the parent is listening for. In the dino counter component in the increment method, let's call the method this.dollar emit and pass in increment and one.

    01:56 Now we can see these incrementing the total, but we need to make sure to capture the dino counter's initial values. In the data function before returning the quantity, let's emit increment and the initial quantity.