uniapp 插槽使用
插槽的基本概念
插槽(Slot)是组件化开发中的重要概念,允许在组件内部预留位置,由父组件动态填充内容。UniApp基于Vue.js,完全支持Vue的插槽机制。
默认插槽使用
父组件通过子组件标签内部的内容传递到子组件的<slot>标签位置。子组件模板中定义<slot>标签作为占位符。
子组件示例代码:
<template>
<view class="child-component">
<slot></slot>
</view>
</template>
父组件调用示例:
<child-component>
<text>这是插入到子组件的内容</text>
</child-component>
具名插槽使用
当需要多个插槽时,使用具名插槽实现精准内容分发。子组件通过name属性命名插槽,父组件通过v-slot指令指定插槽名称。
子组件定义多个插槽:
<template>
<view>
<slot name="header"></slot>
<slot name="content"></slot>
<slot name="footer"></slot>
</view>
</template>
父组件按名称分发内容:
<child-component>
<template v-slot:header>
<text>头部内容</text>
</template>
<template v-slot:content>
<text>主体内容</text>
</template>
<template v-slot:footer>
<text>底部内容</text>
</template>
</child-component>
作用域插槽使用
当子组件需要向插槽传递数据时,使用作用域插槽。子组件在<slot>标签上绑定属性,父组件通过v-slot接收数据。
子组件绑定数据:
<template>
<view>
<slot :item="itemData" :index="currentIndex"></slot>
</view>
</template>
<script>
export default {
data() {
return {
itemData: { name: '示例数据' },
currentIndex: 1
}
}
}
</script>
父组件接收数据:
<child-component>
<template v-slot="slotProps">
<text>接收到的数据:{{slotProps.item.name}}</text>
<text>索引值:{{slotProps.index}}</text>
</template>
</child-component>
插槽默认内容设置
子组件可以在<slot>标签内设置默认内容,当父组件没有提供插槽内容时显示。
子组件设置默认内容:
<template>
<view>
<slot>这是默认显示的内容</slot>
</view>
</template>
动态插槽名
通过方括号语法使用动态插槽名,实现更灵活的插槽分发。
父组件动态指定插槽:
<child-component>
<template v-slot:[dynamicSlotName]>
<text>动态插槽内容</text>
</template>
</child-component>
<script>
export default {
data() {
return {
dynamicSlotName: 'header'
}
}
}
</script>
注意事项
使用插槽时组件必须有闭合标签,单标签写法会导致插槽内容无法正常渲染。作用域插槽的数据流动是单向的,父组件不能直接修改子组件传递的数据。在UniApp中,部分小程序平台对插槽的支持存在差异,建议进行兼容性测试。







