List rendering in Vue.js involves rendering a list of items dynamically based on an array or an object. Vue.js provides several directives to handle list rendering. Here are some common techniques for list rendering in Vue.js:
-
v-for
Directive: Thev-for
directive is used to iterate over an array and render elements for each item in the array.<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template><script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
};
</script>
The
:key
attribute is essential when usingv-for
to help Vue.js efficiently update the DOM. -
v-for
with Index: You can also access the index of the current iteration usingv-for
.<template>
<ul>
<li v-for="(item, index) in items" :key="index">{{ index + 1 }}. {{ item.name }}</li>
</ul>
</template><script>
export default {
data() {
return {
items: [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
]
};
}
};
</script>
-
Rendering an Object with
v-for
: You can usev-for
to iterate over the properties of an object.<template>
<ul>
<li v-for="(value, key) in user" :key="key">{{ key }}: {{ value }}</li>
</ul>
</template><script>
export default {
data() {
return {
user: {
name: 'John Doe',
age: 25,
email: '[email protected]'
}
};
}
};
</script>
-
v-for
withv-if
: You can combinev-for
withv-if
to conditionally render items.<template>
<ul>
<li v-for="item in items" :key="item.id" v-if="item.status === 'active'">
{{ item.name }}
</li>
</ul>
</template><script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1', status: 'active' },
{ id: 2, name: 'Item 2', status: 'inactive' },
{ id: 3, name: 'Item 3', status: 'active' }
]
};
}
};
</script>
Comments