uniapp 如何使用自定义插槽 slot
在 uni-app 中使用自定义插槽(slots)可以让开发者在封装的组件内部定义可替换内容区域,从而实现高度定制化的组件复用。以下是如何在 uni-app 中使用自定义插槽的基本步骤:
默认插槽(匿名插槽)的使用
子组件定义:
在子组件(例如 slot-one.vue
)的模板中,使用 <slot>
标签定义一个默认插槽。
<!-- slot-one.vue --> <template> <view class="slot-item"> <!-- 默认插槽位置 --> <slot></slot> </view> </template>
父组件使用:
在父组件中引入并使用子组件,并在子组件标签内部编写你想要替换的内容。
<!-- 父组件.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>
具名插槽的使用
子组件定义:
在子组件中可以定义多个具名插槽,每个具名插槽有自己的名称。
<!-- slot-one.vue --> <template> <view class="slot-item"> <!-- 具名插槽 example1 --> <slot name="header">默认头部内容</slot> <!-- 具名插槽 example2 --> <slot name="body">默认主体内容</slot> <!-- 其他内容... --> </view> </template>
父组件使用:
父组件可以通过 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 中,作用域插槽用于从子组件向插槽内容传递数据:
子组件定义:
子组件提供作用域插槽的值。
<!-- 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>
父组件使用:
父组件接收并使用这些值。
<!-- 父组件.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 的规范在组件内部定义插槽,并在父组件中正确使用即可。
到此这篇关于uniapp 如何使用自定义插槽 slot的文章就介绍到这了,更多相关uniapp 如何使用自定义插槽 slot内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论