以下是一个微信小程序自定义组件的详细教程,覆盖开发文档中的核心知识点。我们将以一个包含属性、事件、插槽、生命周期等功能的按钮组件为例进行说明:
一、创建组件
在 components
目录下新建 custom-button
文件夹,包含以下文件:
- custom-button.json(组件配置)
{
"component": true,
"usingComponents": {},
"styleIsolation": "apply-shared" // 允许外部样式影响组件
}
- custom-button.wxml(模板结构)
<view class="button-container">
<!-- 默认插槽 -->
<slot></slot>
<!-- 具名插槽 -->
<slot name="icon"></slot>
<!-- 作用域插槽 -->
<slot name="badge" slot-scope="props">
<view class="badge">{{props.count}}</view>
</slot>
</view>
- custom-button.wxss(样式文件)
.button-container {
padding: 12rpx 24rpx;
border-radius: 8rpx;
background-color: {{buttonColor}};
color: white;
display: flex;
align-items: center;
justify-content: center;
}
.badge {
position: absolute;
top: -8rpx;
right: -8rpx;
width: 20rpx;
height: 20rpx;
border-radius: 50%;
background-color: red;
font-size: 12rpx;
display: flex;
align-items: center;
justify-content: center;
}
- custom-button.js(逻辑实现)
Component({
// 组件属性定义
properties: {
buttonColor: {
type: String,
value: '#409eff',
observer: function(newVal, oldVal) {
console.log(`颜色变化:${oldVal} -> ${newVal}`);
}
},
disabled: Boolean
},
// 组件数据
data: {
count: 0
},
// 生命周期
lifetimes: {
created() {
console.log('组件实例被创建');
},
attached() {
console.log('组件被添加到页面');
},
ready() {
console.log('组件渲染完成');
},
detached() {
console.log('组件被移除');
}
},
// 数据监听器
observers: {
'count': function(newCount) {
this.triggerEvent('countChange', { value: newCount });
}
},
// 组件方法
methods: {
handleClick() {
if (!this.properties.disabled) {
this.setData({ count: this.data.count + 1 });
this.triggerEvent('click', { timestamp: Date.now() });
}
},
// 供父组件调用的方法
resetCount() {
this.setData({ count: 0 });
}
}
})
二、在页面中使用组件
- 页面JSON配置
{
"usingComponents": {
"custom-button": "/components/custom-button/custom-button"
}
}
- 页面WXML结构
<custom-button
buttonColor="#ff4d4f"
disabled="{{false}}"
bind:click="handleButtonClick"
>
<!-- 默认插槽内容 -->
<view>点击次数:{{count}}</view>
<!-- 具名插槽 - 图标 -->
<image slot="icon" src="/images/icon.png" mode="aspectFit"></image>
<!-- 作用域插槽 - 徽章 -->
<view slot="badge" slot-scope="props">
<text>{{props.count > 0 ? props.count : ''}}</text>
</view>
</custom-button>
<button bindtap="resetButton">重置计数</button>
- 页面JS逻辑
Page({
data: {
count: 0
},
handleButtonClick(e) {
console.log('按钮点击事件:', e.detail);
this.setData({ count: e.detail.value });
},
resetButton() {
const buttonComponent = this.selectComponent('.custom-button');
buttonComponent.resetCount();
}
})
三、核心知识点说明
- 组件属性(Properties)
- 支持类型校验和默认值设置
- 通过
observer
监听属性变化 - 支持静态和动态绑定
- 事件系统(Events)
- 自定义事件通过
triggerEvent
触发 - 支持事件参数传递
- 父组件通过
bind:事件名
监听
- 插槽(Slots)
- 默认插槽(无名称)
- 具名插槽(通过
slot
属性指定) - 作用域插槽(通过
slot-scope
传递数据)
- 生命周期(Lifetimes)
- created: 组件实例化时触发
- attached: 组件添加到页面时触发
- ready: 组件渲染完成时触发
- detached: 组件从页面移除时触发
- 数据监听器(Observers)
- 监听数据字段变化
- 支持通配符匹配
- 可执行异步操作
- 样式隔离(Style Isolation)
isolated
:默认模式,样式不影响外部apply-shared
:允许外部样式影响组件shared
:组件样式会影响外部
- 组件方法(Methods)
- 内部方法直接定义在
methods
中 - 父组件通过
selectComponent
调用子组件方法 - 支持参数传递和返回值
四、扩展功能实现
- 使用Behaviors共享代码
// 创建behavior
module.exports = Behavior({
properties: {
theme: {
type: String,
value: 'default'
}
},
methods: {
changeTheme(newTheme) {
this.setData({ theme: newTheme });
}
}
});
// 在组件中使用
const themeBehavior = require('./theme.behavior');
Component({
behaviors: [themeBehavior],
// ...其他配置
})
- 父子组件通信高级用法
- 父组件通过
属性绑定
修改子组件属性,子组件通过 properties 接收父组件传递的属性,并定义类型和默认值 - 子组件通过
triggerEvent
向父组件传递复杂数据 - 微信小程序中的父子组件通信示例
- 动态组件加载
// 动态加载组件
const CustomButton = require('./custom-button/custom-button');
const button = new CustomButton();
button.setData({ buttonColor: '#409eff' });
- 插槽内容分发控制
<!-- 组件模板 -->
<view class="button-container">
<slot name="icon" wx:if="{{showIcon}}"></slot>
<slot></slot>
</view>
五、调试与优化建议
- 开发者工具调试技巧:
- 使用
console.log
输出组件状态 - 通过
WXML 结构
面板查看插槽内容 - 在
Sources
面板设置断点调试生命周期
- 性能优化:
- 避免在
ready
生命周期中执行耗时操作 - 使用
observers
替代频繁的setData
- 对插槽内容进行合理的条件渲染
- 错误处理:
- 在
error
生命周期中捕获异常 - 对外部传入的属性进行类型校验
- 使用
try...catch
包裹异步操作
通过以上示例,我们完整覆盖了微信小程序组件开发的核心知识点。开发者可以根据实际需求扩展组件功能,例如添加动画效果、支持更多事件类型或集成云开发能力。建议在实际项目中结合官方文档(微信小程序组件开发文档)进行深入学习。