VueJS

Creating Dynamic Lists with Vue.js v-for Directive


Introduction to Vue.js v-for Directive

In Vue.js, the `v-for` directive is used to render lists of items by iterating over an array or an object. This guide will walk you through using the `v-for` directive to create dynamic lists in your Vue.js applications.

Rendering Lists with v-for

The `v-for` directive is used within an HTML element to render a list of items. It allows you to loop through an array and render elements for each item in the array. Here's an example:

<div id=`app`>
    <ul>
        <li v-for=`item in items`>{{ item }}</li>
    </ul>
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            items: ['Apple', 'Banana', 'Cherry', 'Date']
        }
    });
</script>
        

In this example, the `v-for` directive is used to loop through the `items` array, and a list item is rendered for each item in the array.

Using Index in v-for

You can also access the index of the current item when using `v-for`. Here's an example of displaying both the item and its index:

<div id=`app`>
    <ul>
        <li v-for=`(item, index) in items`>{{ index + 1 }}. {{ item }}</li>
    </ul>
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            items: ['Apple', 'Banana', 'Cherry', 'Date']
        }
    });
</script>
        

In this example, the `index` variable represents the index of the current item in the array, and it's used to display item numbers.

Conclusion

The `v-for` directive in Vue.js is a powerful tool for rendering dynamic lists. It allows you to easily loop through arrays and objects, rendering elements based on your data. This is essential for creating dynamic and data-driven web applications.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.