Create a List Component in Vue.js

    Greg ThomanGreg Thoman

    In this lesson, we will learn how to iterate over an array in a Vue.js template using the v-for property. We can add to and remove from that list using v-on:click and v-on:keypress.enter.



    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 Here we have our basic Vue component. Let's get rid of our content attribute and replace it with a list called items. Each item will have a text attribute that we'll set to a string. We'll set this first one to "velociraptor." We'll set the next one to "triceratops." Our last one will be "stegosaurus."

    00:22 Let's add this list to our template. We're going to get rid of our content div and add a list. To iterate over our items array, we need our templates to make use of the V4 property. We're going to have for item in items.

    00:36 Each time that iterates, we're going to make use of the item.text property. Let's create a way to add items to this list dynamically. Let's create an input field with the ID of itemform. Then we'll create an add dinosaur button.

    00:51 We need a way for this button in our template to call a method on our component. In our component, we're going to add a block for methods, and then we're going to add a method called addItem. Here we're going to set the variable input equal to itemform.

    01:10 After verifying that the input's value is not an empty string, we're going to push an object into the items array with the text attribute set to the input's value. Then we want to clear out that input. Let's hook up our button to the addItem method by adding the v-on:click property to our button.

    01:28 We'll set that equal to addItem. Let's also allow the user to press enter to add items. We'll do that by using the property v-on:keypress.enter, and setting that to addItem. Now you'll see we can add a T. rex. Let's add a way to remove dinosaurs from our list.

    01:46 In our item iterator, let's add a button with a v-on:click property set to deleteItem. We're going to need to know the index of the clicked item. The for property takes two arguments, the second of which is an index.

    01:58 Let's add that index to our deleteItem call, then let's go to our method struct, and add the deleteItem function. We'll pass the index into this method, and then we'll use that index to splice the item out of the items array. We can get rid of these pesky velociraptors, and add a T. rex and a pachycephalosaurus.