Getting Started with Vue.js: Lesson 8 of 25

Vue Templating: Lists

Up Next

Applying Classes with Vue

Autoplaying in 7 seconds!

Cancel

Displaying lists of data is one of the most common things we need to do in our JavaScript applications. Let's compare how we can do it using plain JavaScript vs Vue.

We'll start with a users array:

let users = [
    {
        name: 'Chris',
        username: 'chrisoncode',
        avatar: 'https://pbs.twimg.com/profile_images/850147482117865472/O28qQSrN_400x400.jpg'
    },
    {
        name: 'Nick',
        username: 'whatnicktweets',
        avatar: 'https://pbs.twimg.com/profile_images/502500686588690432/wXBzuCBj_400x400.jpeg'
    },
    {
        name: 'Holly',
        username: 'hollylawly',
        avatar: 'https://pbs.twimg.com/profile_images/926258409552297985/Vk18Dg9M_400x400.jpg'
    }
];

Showing a List in JavaScript

To show a list, we'll need to use an ES6 template string and write all the code in our JavaScript. The HTML will just be a blank div. This can lead to scalability and readability issues since the HTML template gives no indication that information will be injected there. You as the developer will need to remember exactly what's getting injected where.

Table of Contents

    const userList = document.querySelector('.user-list');
    users.forEach(function(user) {
        const userItem = document.createElement('li');
        userItem.innerHTML = `
            <img src="${user.avatar}" width="200" height="200"><br>
            Name: ${user.name}<br>
            Username: ${user.username}
        `;
    
        userList.appendChild(userItem);
    });

    Displaying a List with Vue

    With Vue, we have a handy directive that we can use to show data in our template: v-for

    To loop over the users in our view, use: <li v-for="user in users"></li>

    const app = new Vue({
        el: '#app',
        data: {
            users: users
        }
    });
    <ul>
        <li v-for="user in users">
            <img :src="user.avatar" width="200" height="200"><br>
            Name: {{ user.name }}<br>
            Username: {{ user.username }}
        </li>
    </ul>

    By declaratively showing our template inside of our HTML, it is extremely clear to ourselves and other developers how the users are injected into this ul and that the source of the data is in Vue.

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.