Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  15] [ 5]  / answers: 1 / hits: 25538  / 7 Years ago, mon, july 3, 2017, 12:00:00

I have a list and a list_item component that I reuse a lot inside my application. On a simplified form:



contact_list.vue



<template lang=pug>
.table
.table-header.table-row
.table-col Contact
.table-col Info

.table-body
contact-list-item(v-for='contact in contacts',
:contact='contact',
@click='doSomething()')

</template>


contact_list_item.vue



<template lang=pug>
.table-row(@click='emitClickEvent')
.table-col {{ contact.name }}
.table-col {{ contact.info }}
</template>


When I use contact_list inside a specific component, I want to be able to send a slot that will add some new columns to the contact_list_item component. This slot will use data of the specific contact that is being rendered inside that contact_list_item component to generate the new columns.



How could I achieve that? Is using slot the best approach?



Thanks in advance.


More From » vue.js

 Answers
26

Slots are the best approach and you will need to use a scoped slot for the contact-list-item component. I'm not really familiar with pug, so I will use HTML for the example.


In contact-list you would add a slot. Notice in this case that the contact is being passed as a property. This is so we can take advantage of scoped slots.


<div class="table">
<div class="table-header table-row">
<div class="table-col">Contact</div>
<div class="table-col">Info</div>
</div>
<div class="table-body">
<contact-list-item v-for='contact in contacts'
:contact="contact"
@click="doSomething"
:key="contact.id">
<slot :contact="contact"></slot>
</contact-list-item>
</div>
</div>

Then add a slot to the contact-list-item.


<div class="table-row" @click="emitClickEvent">
<div class="table-col">{{contact.name}}</div>
<div class="table-col">{{contact.info}}</div>
<slot></slot>
</div>

Finally, in your Vue template, use the scoped template.


<div id="app">
<contact-list :contacts="contacts">
<template scope="{contact}">
<div class="table-col">{{contact.id}}</div>
</template>
</contact-list>
</div>

Here is a working example. I have no idea what your styles are but notice the id column is now displayed in the contact-list-item.


[#57224] Friday, June 30, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;