-
• uniapp 如何使用自定义插槽 slot
-
• 默认插槽(匿名插槽)的使用
-
• 具名插槽的使用
-
• 作用域插槽的使用(Vue 2.x 版本)
-
• 作用域插槽的使用(Vue 3.x 版本)
-
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 的规范在组件内部定义插槽,并在父组件中正确使用即可。
原文始发于微信公众号(前端爱好者):uni-app 如何使用自定义插槽 slot
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/268711.html