VueJS: Vue Components

in VueJS Basics

In this tutorial we're going to learn how we can create reuseable templates in VueJS by creating Vue components. For this example we're going to re-visit the todo list loop from a previous tutorial.

To recap to create a list item for the todo we needed a HTML template of this

<div id="app">
    <ul>
        <li v-for="todo in todos">
            {{ todo.text }}
        </li>
    </ul>
</div>

Now we're going to swap out the list item element for a reuseable todo-item component that we can reuse anywhere in our app.

To start with we need to change the HTML to replace the list item with the new todo-item component, while keeping the for loop.

<div id="app">
    <ul>
        <todo-item v-for="todo in todos"></todo-item>
    </ul>
</div>

The Vue object is going to be exactly the same as the previous tutorial of having an array of objects used in the todo.

var app = new Vue({
    el: '#app',
    data: {
        todos: [
            { task: 'Learn JavaScript'},
            { task: 'Learn VueJS'},
            { task: 'Build awesome stuff'}
        ]
    }
})

With the data setup and the HTML setup with the new component we need to create the component object.

Vue.component('todo-item', {
    template: '<li>{{ todo.task }}</li>'
})

When you view this in the browser you'll now see it display the todo items on the page but they will not be populated with the text from the todo. This is because each VueJS component is built within it's own scope so we will need to pass the todo object into the component. To pass the value into the component we need to use props which allows the parent object to pass data into the child objects. Our todo-item now changes to this.

Vue.component('todo-item', {
    props: ['todo'],
    template: '<li>{{ todo.task }}</li>'
})

This gives us a todo object in the child component where we can access the task property. To pass these todos into the child component from the parent we need to bind to the current todo object by using the v-bind directive.

<div id="app">
    <ul>
        <todo-item v-for="todo in todos" v-bind:todo="todo"></todo-item>
    </ul>
</div>

Now when you refresh the browser you'll see the list of todo tasks. View the demo to see this in action.

Demo

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email