uniapp 插槽使用
uniapp 插槽的基本使用
插槽(Slot)是组件化开发中的重要特性,允许在组件内部预留位置,由父组件动态传入内容。uniapp 支持 Vue 的插槽语法,包括默认插槽、具名插槽和作用域插槽。
默认插槽示例
子组件中通过 <slot> 标签定义插槽位置:
<!-- 子组件 child.vue -->
<template>
<view class="container">
<slot></slot>
</view>
</template>
父组件使用时,在子组件标签内插入内容:
<!-- 父组件 -->
<child>
<text>这是插入到默认插槽的内容</text>
</child>
具名插槽的使用
当需要多个插槽时,可通过具名插槽区分。子组件用 name 属性命名插槽:
<!-- 子组件 child.vue -->
<template>
<view>
<slot name="header"></slot>
<slot name="footer"></slot>
</view>
</template>
父组件通过 v-slot 或 # 语法指定插槽名:
<!-- 父组件 -->
<child>
<template v-slot:header>
<text>头部内容</text>
</template>
<template #footer>
<text>底部内容</text>
</template>
</child>
作用域插槽的使用
作用域插槽允许子组件向插槽传递数据。子组件在 <slot> 上绑定属性:
<!-- 子组件 child.vue -->
<template>
<view>
<slot name="item" v-for="item in list" :item="item"></slot>
</view>
</template>
<script>
export default {
data() {
return {
list: ['A', 'B', 'C']
}
}
}
</script>
父组件通过 v-slot 接收数据:
<!-- 父组件 -->
<child>
<template v-slot:item="slotProps">
<text>{{ slotProps.item }}</text>
</template>
</child>
插槽的默认内容
子组件可在 <slot> 内设置默认内容,当父组件未传递插槽内容时显示:
<!-- 子组件 child.vue -->
<template>
<view>
<slot>默认显示文本</slot>
</view>
</template>
注意事项
- 兼容性:uniapp 的插槽语法与 Vue 一致,但在小程序端部分高级用法(如动态插槽名)可能受限。
- 样式作用域:插槽内容样式受父组件样式影响,若需隔离样式可使用
style scoped。 - 性能优化:避免在插槽中使用复杂逻辑,尤其是循环嵌套插槽时可能影响渲染性能。
通过合理使用插槽,可以大幅提升组件的灵活性和复用性。







