即插槽,插槽定義在子組件內(nèi),是組件的一塊HTML模板,可以在子組件內(nèi)設(shè)置默認(rèn)值,也可以在父組件內(nèi)定義插槽內(nèi)顯示的內(nèi)容
默認(rèn)插槽,具名插槽和作用域插槽
舉個例子:
<!-- child組件 -->
<template>
<section>
<!-- 具名插槽 -->
<slot name="header">
<header>這是子組件內(nèi)定義header</header>
</slot>
<!-- 匿名插槽 -->
<slot></slot>
<!-- 具名插槽 -->
<slot name="footer">
<footer>這是子組件內(nèi)定義footer</footer>
</slot>
</section>
</template>
<!-- 父組件內(nèi)使用 -->
<template>
<div>
<child>
<div>父組件內(nèi)定義內(nèi)容</div>
<footer slot="footer">父組件內(nèi)定義插槽內(nèi)容</footer>
</child>
</div>
</template>

最終顯示效果
<slot name="header">和<slot name="footer">是具名插槽,在父組件使用時,在<child>標(biāo)簽內(nèi)定義任意標(biāo)簽,并添加屬性slot = “name”,則該標(biāo)簽就會覆蓋組件內(nèi)對用的插槽內(nèi)容。<slot>是匿名插槽,不設(shè)置name屬性,<child>標(biāo)簽內(nèi),不被具名插槽包裹的內(nèi)容,會覆蓋匿名插槽的內(nèi)容。
<!-- child組件 -->
<ul>
<li v-for="todo in todos" :key="todo.id">
<slot :todo="todo">
<!-- 回退的內(nèi)容 -->
{{ todo.text }}
</slot>
</li>
</ul>
<!-- 使用 -->
<child :todos="todos">
<!-- 將 `slotProps` 定義為插槽作用域的名字 -->
<template slot-scope="slotProps">
<span v-if="slotProps.todo.isComplete">?</span>
{{ slotProps.todo.text }}
</template>
</child>
子組件內(nèi),定義slot,綁定todo屬性,在父組件內(nèi)使用時,在child內(nèi),通過slot-scope接受一個對象參數(shù),可以根據(jù)參數(shù),定制每個代辦項(xiàng)。slot-scope="{todo}"可以結(jié)構(gòu)獲取參數(shù)??墒嵌x多個作用域插槽。
針對ElementUI框架Table組件的二次封裝
<!-- 二次封裝 z-table -->
<div>
<el-table :data="rows"
v-loading="loading"
v-bind="$attrs"
v-on="$listeners"
ref="table"
empty-text="沒有滿足條件的數(shù)據(jù)哦!">
<!-- 公共column等等。 -->
<el-table-column v-for="col in columns"
:key="col.colName"
:label="col.viewName"
:width="col.width"
:prop="col.colName"
show-overflow-tooltip>
<!-- 通過slot-scope獲取el-table定義的row -->
<template slot-scope="{row}">
<!-- 將row和col屬性,通過作用域插槽暴露給父組件 -->
<slot :col="col" :row="row">
{{row[col.colName]}}
</slot>
</template>
</el-table-column>
</el-table>
<!-- pagination等其他公共設(shè)置 -->
<div>
<!-- 使用 -->
<z-table :rows="rows" :columns="cols" :loading="loading" checked :page="pages" @changePage="pageChange">
<template slot-scope="{col,row}">
<div v-if="true">
<!-- todo -->
</div>
<div v-else>
{{row[col.colName]}}
</div>
</template>
</z-table>