Example:
In Vue.js, mapping typically refers to iterating over an array of data and rendering components or elements based on that data. There are a few ways to achieve mapping in Vue.js, and one common approach is to use the v-for directive.
Here’s a basic example:
<template>
<div>
<ul>
<!-- Using v-for to iterate over an array -->
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
};
</script>
In this example,
the v-for directive is used to iterate over the items array, and for each item, a list item (<li>) is rendered. The :key attribute is used to provide a unique identifier for each item in the loop, which helps Vue.js efficiently update the DOM.
You can also use v-for it with objects and iterate over key-value pairs. For example:
<template>
<div>
<ul>
<!-- Using v-for to iterate over an object -->
<li v-for="(value, key) in myObject" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
myObject: {
key1: 'Value 1',
key2: 'Value 2',
key3: 'Value 3'
}
};
}
};
</script>
In this case, v-for is used to iterate over the key-value pairs of myObject.
Remember that the v-for directive can be used on a variety of elements, not just <li>. You can use it on components, divs, spans, etc., depending on your specific use case.