List Rendering with v-for and v-slot
Showcase how to use scoped slots with v-for for more complex and customizable list renderings.
// Component that provides the template for a list item
Vue.component('list-item', {
template: '<div><slot :item="item"></slot></div>',
props: ['item']
});
This defines a Vue component named 'list-item', which expects a prop 'item'. The component uses a slot to allow the parent component to customize how the 'item' prop is rendered.
<template>
<div>
<!-- Use v-for with v-slot on the 'list-item' component to render a list -->
<list-item
v-for="(item, index) in items"
:key="index"
:item="item"
v-slot:default="{ item }"
>
<!-- Custom template for the list item using the scoped slot -->
<span class="item-content">{{ item.name }} - {{ item.detail }}</span>
</list-item>
</div>
</template>
<script>
export default {
data() {
return {
items: [{ name: 'Item 1', detail: 'Detail 1' }, { name: 'Item 2', detail: 'Detail 2' }]
};
}
};
</script>
This example uses a Vue template containing the 'list-item' component defined above. The 'v-for' directive is used to render a list of items, each with a custom template defined by the 'v-slot' directive. The 'item' property is a scoped slot prop that allows each instance of the 'list-item' to access its corresponding item data.