Paulund

VueJS - Loop List Elements

Just like other programming languages you'll need to be able to loop through data and perform a common task with each data point. The most common JavaScript data form is JSON where you can construct an object of multiple elements to form your data. Using VueJS it makes it very easy to loop through this data to perform your task. In this tutorial we're going to build a list from data in JSON format. To loop through data VueJS uses the syntax of for single in multiple, where multiple is your array of objects, on each loop cycle your be able to access the current item from the single variable. For this example we need a list of tasks to do.


[
    { text: 'Learn JavaScript'},
    { text: 'Learn VueJS'},
    { text: 'Build awesome stuff'}
]

From the above data we need to build a list, where each point is a list item. To start with we need to add the unordered list element in the HTML.


<div id="app">
    <ul>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>

In the above HTML we have 3 list items, but we want the list to be built from a data file and run through each task. In VueJS this is done by using the directive v-for.


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

This requires a data property of todos, and will loop through each of these todos and create a new todo object each time, the todo object will then print the text property to display the data. Now we can build the Vue object and include the data for the todos.


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

We've built a Vue object with a data property of todos, this has an array of objects which will be used on the page to built the list. Now when you view this in the browser you'll see the list with these 3 tasks on the page. In a real world example you would replace the data JSON with an API GET call to collect the JSON data. Because Vue data points are reactive and linked to the DOM we can add a new item to this list from the console. Simply open your console and type in the command app.todos.push({ text: 'New list item' }), you'll automatically see this new item added to the list.