以下是一個微信小程序自定義組件的詳細教程,覆蓋開發文檔中的核心知識點。我們將以一個包含屬性、事件、插槽、生命周期等功能的按鈕組件為例進行說明:
一、創建組件
在 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
包裹異步操作
通過以上示例,我們完整覆蓋了微信小程序組件開發的核心知識點。開發者可以根據實際需求擴展組件功能,例如添加動畫效果、支持更多事件類型或集成云開發能力。建議在實際項目中結合官方文檔(微信小程序組件開發文檔)進行深入學習。