To dynamically render multiple instances of a component using v-for in Vue, we need to ensure that each component has a unique key.
// In ChildComponents.vue <template> <div> <span> {{ data.name }} </span> </div> </template> <script> export default { name: "ChildComponent", props: ['data'] }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Note: ChildComponent receives the "data" prop from the parent component and displays the "name" of the item.
// In ParentComponents.vue <template> <div> <ChildComponent v-for="(item) in items" :key="item.id" :data="item" /> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { items: [ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' } ] }; } }; </script>
We use "v-for" to iterate over the items array.
For each "item" in the array, we render an instance of the "ChildComponent".
We bind the key attribute to "item.id" to ensure that each component instance has a unique key. This helps Vue.js efficiently update the DOM when the array changes.
We pass each "item" as a prop named "data" to the "ChildComponent".
This approach allows us to dynamically render multiple instances of a component based on an array of data in Vue.
Each component instance receives its respective "data" item as a prop, making it easy to customize the rendering and behaviour of each component instance.