在循环中使用slot插槽时的传值方法、组件中遍历插槽
这几天在写一个list组件,写的时候遇到一点问题。话不多说,上代码。part1:使用 List 组件循环 ListItem组件<template><div style="border: 5px solid blue;padding: 10px 50px;"><h2 style="color: blue;">oldfather</h2><List
·
这几天在写一个list组件,写的时候遇到一点问题。话不多说,上代码。
part1:使用 List 组件循环 ListItem组件
<template>
<div style="border: 5px solid blue;padding: 10px 50px;">
<h2 style="color: blue;">oldfather</h2>
<List :dataList="list" v-slot:fatherSlot="{item}">
<ListItem slot="fatherSlot">
<div slot="child">{{item.title}}</div>
</ListItem>
</List>
</div>
</template>
<script>
import List from './List';
import ListItem from './ListItem';
export default {
name:'OldFather',
components: {
ListItem,
List
},
data () {
return {
list:[
{'title':"山中高士晶莹雪"},
{'title':"世外仙株寂寞林"},
{'title':"千红一哭,万艳同悲"},
]
}
}
}
</script>
part2:List组件的内容
<template>
<div style="border: 5px solid red;padding: 10px 100px;">
<h2 style="color:red">father</h2>
<template v-for="item in dataList">
<slot name="fatherSlot" :item="item"></slot>
</template>
</div>
</template>
<script>
import ListItem from './ListItem';
export default {
name:'List',
components: {
ListItem
},
props: {
dataList:{
type: Array,
default: () => []
}
}
}
</script>
part3:ListItem组件的内容
<template>
<div style="border: 5px solid green;margin: 20px;">
<h4 style="color: green;">child</h4>
<slot name="child"></slot>
</div>
</template>
<script>
export default {
name:'ListItem',
}
</script>
part4:效果

总结出下面三种写法:
1、v-slot
<List :dataList="list" v-slot:fatherSlot="{item}">
<ListItem slot="fatherSlot">
<div slot="child">{{item.title}}</div>
</ListItem>
</List>
2、v-slot
<List :dataList="list" v-slot:fatherSlot="slotProps">
<ListItem slot="fatherSlot">
<div slot="child">{{slotProps.item.title}}</div>
</ListItem>
</List>
3、slot-scope
<List :dataList="list" >
<ListItem slot="fatherSlot" slot-scope="slotProps">
<div slot="child">{{slotProps.item.title}}</div>
</ListItem>
</List>
更多推荐



所有评论(0)