插槽 slot
插槽(slot)让组件的内容由使用者决定:组件模板里写 <slot></slot> 占位,父组件在标签内写的内容会被填进去。相当于「组件是壳子,内容外部塞」。
进阶用法:具名插槽 <slot name="header"> 配合 v-slot:header(缩写 #header)分发多块内容;作用域插槽把子组件数据传回父组件 <slot :item="data">,父端用 v-slot="{ item }" 接收——列表组件的每一行怎么渲染由使用者定。
- 默认插槽:
占位,外部内容填进去 - 具名插槽:#header / #footer 分发多块内容
- 作用域插槽:子组件把数据回传给父组件渲染(v-slot="{ item }")
HTML
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>插槽 slot</title> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> </head> <body> <div id="app"> <!-- 默认插槽 + 具名插槽 --> <my-panel> <template #header><b>面板标题</b></template> 默认内容写在这里 <template #footer>底部信息</template> </my-panel> <!-- 作用域插槽:列表怎么渲染由我决定 --> <my-list :items="fruits"> <template v-slot="{ item }"> <li style="color: #42b883">{{ item.name }} - {{ item.price }} 元</li> </template> </my-list> </div> <script> const { createApp, ref } = Vue; const app = createApp({ setup() { const fruits = ref([{ name: '苹果', price: 6 }, { name: '梨', price: 5 }]); return { fruits }; } }); app.component('my-panel', { template: ` <div style="border:1px solid #ddd;padding:12px;margin:8px"> <div class="hd"><slot name="header"></slot></div> <div><slot></slot></div> <div class="ft"><slot name="footer"></slot></div> </div>` }); app.component('my-list', { props: ['items'], template: `<ul><slot v-for="i in items" :key="i.name" :item="i"></slot></ul>` }); app.mount('#app'); </script> </body> </html>
本节要点插槽让组件「内容外置」:默认插槽填内容,具名插槽分区域,作用域插槽把数据交还调用方。




