作用域插槽
子组件通过插槽将数据传给父组件。
父组件通过slot-scope或者v-slot接收一个子组件传递的Object数据,key为prop名称,value为prop的值。
父组件:
<template>
<div>
<CardList>
<template slot="cardList" slot-scope="cardData">
<h4>{{cardData.otherData}}</h4>
<ul>
<li v-for="item in cardData.list">
{{item}}
</li>
</ul>
</template>
</CardList>
<CardList>
<template v-slot:cardList="cardData">
<h4>{{cardData.otherData}}</h4>
<ul>
<li v-for="item in cardData.list">
{{item}}
</li>
</ul>
</template>
</CardList>
</div>
</template>
<script>
import CardList from "./slotTest/CardList";
export default {
name: 'HelloWorld',
components: {CardList}
}
</script>
子组件:
<template>
<div class="slot-test">
<h3>我是卡片列表组件</h3>
<slot name="cardList" :list="list" :otherData="'这是标题数据'"/>
</div>
</template>
<script>
export default {
name: "CardList",
props: {
},
data() {
return {
list: [
{name: '卡1', content: '这是卡1'},
{name: '卡2', content: '这是卡2'},
{name: '卡3', content: '这是卡3'}
]
}
}
}
</script>