以下是一个微信小程序自定义组件的详细教程,覆盖开发文档中的核心知识点。我们将以一个包含属性、事件、插槽、生命周期等功能的按钮组件为例进行说明:
在 components
目录下新建 custom-button
文件夹,包含以下文件:
{
"component": true,
"usingComponents": {},
"styleIsolation": "apply-shared" // 允许外部样式影响组件
}
<view class="button-container">
<slot>slot>
<slot name="icon">slot>
<slot name="badge" slot-scope="props">
<view class="badge">{{props.count}}view>
slot>
view>
.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;
}
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 });
}
}
})
{
"usingComponents": {
"custom-button": "/components/custom-button/custom-button"
}
}
<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>
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();
}
})
observer
监听属性变化triggerEvent
触发bind:事件名
监听slot
属性指定)slot-scope
传递数据)isolated
:默认模式,样式不影响外部apply-shared
:允许外部样式影响组件shared
:组件样式会影响外部methods
中selectComponent
调用子组件方法// 创建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
包裹异步操作通过以上示例,我们完整覆盖了微信小程序组件开发的核心知识点。开发者可以根据实际需求扩展组件功能,例如添加动画效果、支持更多事件类型或集成云开发能力。建议在实际项目中结合官方文档(微信小程序组件开发文档)进行深入学习。