Reputation: 17591
How to send item from v-for to slot? In vue.js.
ListComponent:
<ul>
<li v-for="item in list">
<slot></slot>
</li>
</ul>
Page view:
<list-component :list="list">
<span v-text="item.value"></span>
</list-component>
Code <span v-text="item.value"></span>
can't access item
(from component's scope). Is it a way to send an item
from component to code in tag?
P.S. I know, that as a workaround I can send $index
from component to parent view, but it's a little bit hacky
UPD: Example of my current workaround (somebody may find this useful):
Declare index
in view's data:
data () {
return {
index: 0,
list: [ ... ]
}
Add to index
param to the view's template:
<list-component :list="list" :index="index">
<span v-text="list[index].value"></span>
</list-component>
Declare index
in component's props:
props: {
index: {
type: Number
}
}
Add index to v-for
's element:
<ul>
<li v-for="item in list" index="$index">
<slot></slot>
</li>
</ul>
Upvotes: 4
Views: 4539
Reputation: 3863
the bind expression is compiled in the context who define them,so:
v-text="item.value"
can not be compiled because in Page view there is no "item" defined.
maybe you can try to change your code structure like below:
ListComponent:
//content in component
<span>i am text in component,item value is:{{item.value}}</span>
<slot></slot>
Page view:
<ul>
<li v-for="item in list">
<list-component :item="item"></list-component>
</li>
</ul>
Upvotes: 3