即插槽,插槽定義在子組件內(nèi)爱榕,是組件的一塊HTML模板,可以在子組件內(nèi)設置默認值藻三,也可以在父組件內(nèi)定義插槽內(nèi)顯示的內(nèi)容
默認插槽,具名插槽和作用域插槽
舉個例子:
<!-- 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>
標簽內(nèi)定義任意標簽逾苫,并添加屬性slot = “name”
,則該標簽就會覆蓋組件內(nèi)對用的插槽內(nèi)容。<slot>
是匿名插槽秘噪,不設置name屬性指煎,<child>
標簽內(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ù)重绷,定制每個代辦項膜毁。slot-scope="{todo}"
可以結構獲取參數(shù)星立≡岬剩可是定義多個作用域插槽。
針對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等其他公共設置 -->
<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>