在頁面開發中,通常一個頁面分為頭部,尾部,和中心內容區。其中頭部,尾部一般比較固定,而中心區域往往是多樣的,需要自定義開發。此時,我們可以引入slot(插槽)來實現這一目標。<slot>
?作為一個占位符,父組件傳遞進來的內容就會渲染在這里。
下面使用slot來實現2個頁面中心區域的差異化開發:
項目結構如下:
1.在項目組件components文件夾里新建一個組件:xxy-layout,在xxy-layout.vue文件寫入下面的代碼:
<template><view class="layout"><view class="header">header區</view><view class="main"><slot></slot></view><view class="footer">底部區</view></view>
</template><script setup></script><style lang="scss" scoped>.layout{.header{height: 100px;background: #cfcfcf;}.main{min-height: 200px;}.footer{height: 120px;background: orange;}}
</style>
?2.在demo1和demo2分別引入xxy-layout組件
demo1:
<template><view><xxy-layout><view class="row" v-for="item in 10">每一行{{item}}</view></xxy-layout></view>
</template>
demo2:
<template><view><xxy-layout><view class="box1"></view><view class="box2"></view></xxy-layout></view>
</template><script setup></script><style lang="scss" scoped>.box1{width: 100px;height: 100px;background: yellowgreen;}.box2{width: 100px;height: 100px;background: yellow;}
</style>
?從而實現中心區域的差異化
如果一個頁面多處需要用到slot,就需要用到具名插槽。此時demo1和demo2還像上面寫,將會失效。對上面xxy-layout.vue進行調整,分別在header和main引入slot,此時需要添加name以示區分。
<view class="header"><slot name="header"></slot>
</view>
<view class="main"><slot name="main"></slot>
</view>
此時再來看頁面,中間的內容消失了,demo2也是一樣。
因此使用具名插槽后,需要對引入子組件部分進行調整,
方法1:通過template v-slot來實現
<xxy-layout><template v-slot:header>demo1頭部</template><template v-slot:main>demo1中心區</template>
</xxy-layout>
效果:
方法2:使用#插槽名稱
<xxy-layout><template #header>demo2頭部</template><template #main>demo2中心區</template>
</xxy-layout>
效果: