概念
在Vue中,插槽(Slots)是一種用于組件模板中的特殊語(yǔ)法,用于實(shí)現(xiàn)組件的內(nèi)容分發(fā)和復(fù)用。插槽允許父組件在子組件的模板中插入任意的內(nèi)容,從而實(shí)現(xiàn)更靈活的組件組合和定制
默認(rèn)插槽(Default Slot)
默認(rèn)插槽是最常用的插槽類型。在子組件的模板中,使用<slot></slot>標(biāo)簽定義默認(rèn)插槽的位置。父組件在使用子組件時(shí),可以在子組件的標(biāo)簽內(nèi)放置內(nèi)容,這些內(nèi)容將被插入到子組件模板中的默認(rèn)插槽位置
父組件文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-745188.html
<template>
<div>
<LearnSlot2>
任意內(nèi)容
</LearnSlot2>
</div>
</template>
<script>
import LearnSlot2 from "./learn-slot2.vue";
export default {
components: {
LearnSlot2,
},
};
</script>
子組件
<template>
<div>
<slot></slot>
</div>
</template>
具名插槽(Named Slots)
除了默認(rèn)插槽,Vue還支持具名插槽。具名插槽允許在子組件中定義多個(gè)命名插槽,父組件可以根據(jù)插槽的名稱來(lái)插入內(nèi)容。在子組件的模板中,使用<slot name="slotName"></slot>標(biāo)簽定義具名插槽的位置,并為每個(gè)插槽指定一個(gè)唯一的名稱。在父組件使用子組件時(shí),使用具名插槽的語(yǔ)法來(lái)插入相應(yīng)名稱的內(nèi)容。
父組件
<template>
<div>
<LearnSlot2>
<!-- <h1>一級(jí)標(biāo)題</h1> -->
<!--
# 后面是插槽的名字
-->
<template #footer>
<div>底部</div>
</template>
<template #header>
<div>頭部</div>
</template>
<template #content>
<div>內(nèi)容</div>
</template>
</LearnSlot2>
</div>
</template>
<script>
import LearnSlot2 from "./learn-slot2.vue";
export default {
components: {
LearnSlot2,
},
};
</script>
子組件
<template>
<div>
一個(gè)組件
<!--
使用slot這個(gè)組件展示
組件標(biāo)簽中間的內(nèi)容
-->
<!--
使用name跟上插槽的名字
-->
<slot name="header"></slot>
<slot name="content"></slot>
<slot name="footer"></slot>
</div>
</template>
作用域插槽(Scoped Slots)
作用域插槽是一種特殊的插槽類型,它允許slot組件向子組件傳遞數(shù)據(jù),并且子組件可以在插槽中使用該數(shù)據(jù)進(jìn)行渲染。
父組件
<!-- ParentComponent.vue -->
<template>
<div>
<h1>Parent Component</h1>
<ListComponent>
<!-- 使用作用域插槽來(lái)渲染列表項(xiàng) -->
<template v-slot="{ item }">
<li>{{ item.name }}</li>
</template>
</ListComponent>
</div>
</template>
<script>
import ListComponent from './ListComponent.vue';
export default {
components: {
ListComponent
}
}
</script>
子組件文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-745188.html
<!-- ListComponent.vue -->
<template>
<div>
<h2>List Component</h2>
<ul>
<slot v-for="item in items" :item="item" :key="item.id"></slot>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
}
</script>
到了這里,關(guān)于第十八節(jié)——插槽的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!