In Vue.js, the v-for directive is a highly effective way to render a list based on an array. This directive can be applied to <template> tags, HTML elements, or components. Here's how to use it:
Basic Usage
Assume you have a component data property named items, which is an array containing several elements. You can use v-for to render a list:
html<template> <div> <ul> <!-- Use v-for to generate li tags for each item --> <li v-for="item in items" :key="item.id"> {{ item.text }} </li> </ul> </div> </template> <script> export default { data() { return { items: [ { id: 1, text: 'Apple' }, { id: 2, text: 'Banana' }, { id: 3, text: 'Orange' } ] } } } </script>
Key Point: Using :key
When using v-for, it is highly recommended to bind a unique key attribute. This key attribute helps Vue identify the identity of each node in the list, enabling efficient updates and reuse.
Using Index
Sometimes you may need to use the index of each element in the list; v-for can also provide the index:
html<li v-for="(item, index) in items" :key="item.id"> {{ index }} - {{ item.text }} </li>
Using v-for on Objects
v-for can also be used to iterate over object properties. For example, if you have an object with multiple properties you want to iterate:
html<ul> <li v-for="(value, name, index) in myObject" :key="index"> {{ index }}. {{ name }}: {{ value }} </li> </ul>
Where myObject might be defined as:
javascriptdata() { return { myObject: { firstName: 'John', lastName: 'Doe', age: 30 } } }
Summary
Using v-for is a powerful way to create repeated content in Vue, whether handling arrays or objects. As you can see, it is very flexible and can handle various complex data structures. By properly using key, Vue can optimize the DOM update process, improving performance. When developing with v-for, you can build dynamic list displays, enhancing the interactivity and user experience of your application.