uniapp 如何使用自定义插槽 slot
在 uni-app 中使用自定义插槽(slots)可以让开发者在封装的组件内部定义可替换内容区域,从而实现高度定制化的组件复用。
以下是如何在 uni-app 中使用自定义插槽的基本步骤:
默认插槽(匿名插槽)的使用
1. 子组件定义:在子组件(例如 slot-one.vue
)的模板中,使用 <slot>
标签定义一个默认插槽。
<!-- slot-one.vue -->
<template>
<view class="slot-item">
<!-- 默认插槽位置 -->
<slot></slot>
</view>
</template>
2. 父组件使用:在父组件中引入并使用子组件,并在子组件标签内部编写你想要替换的内容。
<!-- 父组件.vue -->
<template>
<view>
<slot-one>
<!-- 这里的内容会被替换到子组件的 slot 内 -->
<view>这是父组件传递给子组件的默认插槽内容</view>
</slot-one>
</view>
</template>
<script>
import SlotOne from '@/components/slot-one.vue'
export default {
components: {
SlotOne,
},
}
</script>
具名插槽的使用
1. 子组件定义:在子组件中可以定义多个具名插槽,每个具名插槽有自己的名称。
<!-- slot-one.vue -->
<template>
<view class="slot-item">
<!-- 具名插槽 example1 -->
<slot name="header">默认头部内容</slot>
<!-- 具名插槽 example2 -->
<slot name="body">默认主体内容</slot>
<!-- 其他内容... -->
</view>
</template>
2. 父组件使用:父组件可以通过 v-slot
指令配合插槽名称来填充不同内容。
<!-- 父组件.vue -->
<template>
<view>
<slot-one>
<!-- 填充具名插槽 header -->
<template v-slot:header>
<view>这是父组件传递给子组件的头部插槽内容</view>
</template>
<!-- 填充具名插槽 body -->
<template v-slot:body>
<view>这是父组件传递给子组件的主体插槽内容</view>
</template>
</slot-one>
</view>
</template>
作用域插槽的使用(Vue 2.x 版本)
在 Vue 2.x 中,作用域插槽用于从子组件向插槽内容传递数据:
1. 子组件定义:子组件提供作用域插槽的值。
<!-- slot-one.vue (Vue 2.x) -->
<template>
<view class="slot-item">
<slot :item="scopedItem">
<!-- 子组件提供的默认内容 -->
{{ scopedItem.defaultText }}
</slot>
</view>
</template>
<script>
export default {
data() {
return {
scopedItem: {
defaultText: '这是子组件提供的默认内容',
// 其他数据...
},
};
},
};
</script>
2. 父组件使用:父组件接收并使用这些值。
<!-- 父组件.vue (Vue 2.x) -->
<template>
<view>
<slot-one>
<template slot="item" slot-scope="{ item }">
<view>这是从子组件获取的:{{ item.text }}</view>
</template>
</slot-one>
</view>
</template>
作用域插槽的使用(Vue 3.x 版本)
在 Vue 3.x 中,作用域插槽改为了 v-slot
函数语法:
<!-- 子组件.vue (Vue 3.x) -->
<template>
<view class="slot-item">
<slot let:item="scopedItem">
{{ scopedItem.defaultText }}
</slot>
</view>
</template>
<script>
export default {
setup() {
const scopedItem = reactive({
defaultText: '这是子组件提供的默认内容',
// 其他数据...
});
return {
scopedItem,
};
},
};
</script>
<!-- 父组件.vue (Vue 3.x) -->
<template>
<view>
<slot-one>
<template #default="{ item }">
<view>这是从子组件获取的:{{ item.text }}</view>
</template>
</slot-one>
</view>
</template>
总结起来,uni-app 中使用自定义插槽的原理与 Vue.js 一致,只需按照 Vue.js 的规范在组件内部定义插槽,并在父组件中正确使用即可。
更多干货🎁
如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “👍点赞” “✍️评论” “💙收藏” 一键三连哦!
【👇🏻👇🏻👇🏻关注我| 获取更多源码 | 优质文章】 带您学习各种前端插件、3D炫酷效果、图片展示、文字效果、以及整站模板 、大学生毕业HTML模板 、期末大作业模板 、等!
以上内容技术相关问题😈欢迎一起交流学习🔥嘉vx+18634371151
—— 往期推荐 ——
更多内容请前往我的首页侧边栏有专栏哦~!
......
....
..