- 使用场景:父组件需要使用到子组件的data时
例子
-
父组件有list数组,传递给子组件,子组件将数组中的属性全部显示出来,但是用什么标签显示这些属性不确定(使用插槽)
-
父组件传递插槽内容过去替换子组件的slot,问题来了,内容是数组项的第几个呢?
-
子组件将数组项内容回传父组件,通过插槽(作用域插槽)
父组件
- 核心代码
<MyTable :arr="list">
<template v-slot="scope">
<img style="width: 100px;" :src="scope.row.headImgUrl" alt="">
</template>
</MyTable>
<template>
<div>
<MyTable :arr="list"></MyTable>
<MyTable :arr="list">
<!-- scope: {row: obj} -->
<template v-slot="scope">
<a :href="scope.row.headImgUrl">{{ scope.row.headImgUrl }}</a>
</template>
</MyTable>
<MyTable :arr="list">
<template v-slot="scope">
<img style="width: 100px;" :src="scope.row.headImgUrl" alt="">
</template>
</MyTable>
</div>
</template>
<script>
import MyTable from "../components/06/MyTable";
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>
子组件
<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>
标签:vue,headImgUrl,name,作用域,插槽,age,组件,cnblog
From: https://www.cnblogs.com/lingxin1123/p/17091592.html