Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    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




    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.