案例描述:循环显示个人信息,在图片一列,因为有可能显示图片链接或是图片,所以我们采用插槽来实现。
涉及到的技术点:父传子通信技术、作用域插槽(在父组件中可获取到子组件中的变量)
实现代码:
父组件UseTable.vue
<template>
<div>
<my-table :arr="list">
<template v-slot="scope">
<a :href="scope.row.headImgUrl">{{ scope.row.headImgUrl }}</a>
</template>
</my-table>
<!-- 显示图片 -->
<my-table :arr="list">
<template v-slot="scope">
<img style="width:100px" :src="scope.row.headImgUrl" alt="">
</template>
</my-table>
</div>
</template>
<script>
import MyTable from '../components/04/MyTable.vue'
export default {
components: {
MyTable,
},
data() {
return {
list: [
{
name: "小传同学",
age: 18,
headImgUrl:
"http://yun.itheima.com/Upload/./Images/20210303/603f2d2153241.jpg",
},
{
name: "小黑同学",
age: 25,
headImgUrl:
"http://yun.itheima.com/Upload/./Images/20210304/6040b101a18ef.jpg",
},
{
name: "智慧同学",
age: 21,
headImgUrl:
"http://yun.itheima.com/Upload/./Images/20210302/603e0142e535f.jpg",
},
],
};
},
};
</script>
<style>
</style>
子组件:MyTable.vue
<template>
<div>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>头像</th>
</tr>
</thead>
<tbody>
<tr v-for="(obj, index) in arr" :key="index">
<td>{{ index + 1 }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.age }}</td>
<td>
<slot :row="obj">
<!-- 默认值给上,如果使用组件不自定义标签显示默认文字 -->
{{ obj.headImgUrl}}
</slot>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: {
arr: Array
}
}
</script>
小结: 插槽可以自定义标签, 作用域插槽可以把组件内的值取出来自定义内容
项目中具名插槽的应用