简介
作用域slot可以简单理解为可以传递参数的slot;通过在子组件slot标签上绑定数据,达到在父组件获取子组件信息的作用。
用法
1、子组件中确定slot的位置,并将需要传递给父组件显示的信息绑定到slot标签上。
<template>
<div class="wrap">
<ul
class="list"
style="border: 1px solid #000; list-style: none; padding: 0"
>
<li
v-for="item in parentData"
style="
list-style: none;
height: 50px;
background: #eee;
border: solid 1px #000;
line-height: 50px;
"
>
<!-- todo绑定的值即为发送给父组件的信息 -->
<slot name='header' :todo="item"></slot>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "sonComponent",
props: {
parentData: {
type: Array,
require: true,
},
},
data() {
return {};
},
methods: {},
};
</script>
2、父组件上通过 slot-scope来获取子组件传递过来的值,并显示出来。需要注意的是slot-scope获取的值并非子组件上直接绑定的值,而是一个包含子组件绑定值的对象,所以需要用“.”来获取。
<template>
<div class="wrap">
<son :parentData="pData">
<!-- 通过slot-scope获取子组件传递的值 -->
<!--此种写法已废弃-->
<!-- <template slot-scope="data"> -->
<template v-slot:header={todo}>
{{ todo.name }}
</template>
</son>
</div>
</template>
<script>
import son from "./son.vue";
export default {
components: { son },
data() {
return {
pd: "hello",
pData: [
{ name: "henry", age: "23", gender: "male" },
{ name: "jason", age: "27", gender: "male" },
{ name: "jasper", age: "25", gender: "male" },
{ name: "tony", age: "23", gender: "male" },
{ name: "lily", age: "21", gender: "female" },
],
};
},
};
</script>
<style>
</style>
应用场景
当父组件需要更改子组件的显示内容但又需要用到子组件的信息时就会用到作用域slot,例如:在表格的单元格内添加按钮来编辑或删除单元格内容。