作用域插槽
子组件
<template>
<div class="list">
<div class="list-title">{{title}}</div>
<ul class="list-content">
<li v-for="(item ,index) in content" :key="index">
<!--这里将content中的每一项数据绑定到slot的item变量上,在父组件中可以获取到item变量-->
<slot :item="item">{{item}}</slot>
</li>
</ul>
</div>
</template>
父组件
<template>
<div>
<MyList title="标题1" :content="listData1"></MyList>
<MyList title="标题2" :content="listData2">
<template slot-scope="scope"> // 为了修改原有子组件的代码,相当于重新写子组件,用slot-scope 可以使父组件获取到数据后修改
<img :src="scope.item.img" width="20">
<span>{{scope.item.text}}</span>
</template>
</MyList>
<MyList title="标题3" :content="listData3">
<template slot-scope="scope">
<b>{{scope.item.prefix ? '有前缀' : '无前缀'}}</b>
<span>{{scope.item.text}}</span>
<span>{{scope.item.remark}}</span>
</template>
</MyList>
</div>
</template>
<script>
import myList from './List.vue';
export default {
name: 'HelloWorld',
components: {
'MyList': myList
},
data() {
return {
listData1: [
'列表项1',
'列表项2',
'列表项3'
],
listData2: [
{text: '第二个列表的列表项1', img: 'example.png'},
{text: '第二个列表的列表项2', img: 'example.png'},
{text: '第二个列表的列表项3', img: 'example.png'}
],
listData3: [
{text: '第三个列表的列表项1', prefix: true, remark: '附加的备注1'},
{text: '第三个列表的列表项2', prefix: false, remark: '附加的备注2'},
{text: '第三个列表的列表项3', prefix: true, remark: '附加的备注3'}
],
}
}
}
</script>

浙公网安备 33010602011771号