學習微信小程序組件之後,一直都是使用別人的組件開發的,剛看到一篇文章講解微信小程序自定義組件通俗易懂的開發案例覺得一看就會自己寫組件了,真的很棒,感謝原作者的手把手教你實現微信小程序中的自定義組件,自己也添加了一些修改(修改部分樣式,添加是否顯示“取消”按鈕功能,添加彈窗淡入淡出動畫,初始化組件賦值操作等一些簡單的東西和註釋化流程提示)。
主要是敲一遍代碼學習之後才體會到原理是這樣子的嘛,光看文檔是看得懂,跟自己做出來真的是兩碼事。
(一)效果展示
1.默認效果:
2.去掉“取消”按鈕效果:
(二)實現流程
創建子組件頁面:
1、新建一個頁面如:components文件夾下的Dailog文件夾下的dialog,注意:該頁面不需要app.json的(聲明的話會報:無效的 pageJSON(components/Dialog/dialog)["component"]
),dialog.json
記得設置:"component": true, // 自定義組件聲明
{
"component": true, // 自定義組件聲明
"usingComponents": {}//引用其他的組件
}
2、編寫wxml/wxss頁面代碼(跟正常pages頁面代碼一樣);
<!--components/Dialog/dialog.wxml-->
<view class='wx_dialog_container' hidden="{{!isShow}}" animation="{{updatePanelAnimationData}}">
<view class='wx-dialog'>
<view class='wx-dialog-title'>{{ title }}</view>
<view class='wx-dialog-content'>{{ content }}</view>
<view class='wx-dialog-footer'>
<view class='wx-dialog-btn' catchtap='_cancelEvent' hidden='{{!isShowCancelBtn}}'>{{ cancelText }}</view>
<view class='wx-dialog-btn' catchtap='_confirmEvent'>{{ confirmText }}</view>
</view>
</view>
</view>
/* components/Dialog/dialog.wxss */
.wx_dialog_container {
position: fixed;
z-index: 999;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.3);
display: flex;
justify-content: center;
align-items: center;
}
.wx-dialog {
width: 80%;
max-width: 600rpx;
background-color: #fff;
text-align: center;
border-radius: 6rpx;
}
.wx-dialog-title {
font-size: 36rpx;
padding: 30rpx 30rpx 10rpx;
}
.wx-dialog-content {
padding: 30rpx 30rpx 10rpx;
min-height: 80rpx;
font-size: 32rpx;
line-height: 1.3;
text-align: justify;
text-justify: newspaper;
word-wrap: break-word;
word-break: break-all;
color: #999;
display: flex;
justify-content: center;
align-items: center;
}
.wx-dialog-footer {
display: flex;
align-items: center;
position: relative;
line-height: 90rpx;
font-size: 34rpx;
}
.wx-dialog-footer::before {
content: '';
position: absolute;
left: 0;
top: 0;
right: 0;
height: 2rpx;
border-top: 2rpx solid #d5d5d6;
color: #d5d5d6;
-webkit-transform-origin: 0 0;
transform-origin: 0 0;
-webkit-transform: scaleY(0.5);
transform: scaleY(0.5);
}
.wx-dialog-btn {
display: block;
-webkit-flex: 1;
flex: 1;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
position: relative;
}
.wx-dialog-footer .wx-dialog-btn:nth-of-type(1) {
color: #353535;
}
.wx-dialog-footer .wx-dialog-btn:nth-of-type(2) {
color: #3cc51f;
}
.wx-dialog-footer .wx-dialog-btn:nth-of-type(2):after {
content: " ";
position: absolute;
left: 0;
top: 0;
width: 2rpx;
bottom: 0;
border-left: 2rpx solid #d5d5d6;
color: #d5d5d6;
-webkit-transform-origin: 0 0;
transform-origin: 0 0;
-webkit-transform: scaleX(0.5);
transform: scaleX(0.5);
}
3、編寫js,這個頁面構造器跟正常的pages頁面的不一樣,可以先參考官方的來寫Component構造器
// components/Dialog/dialog.js
// 子組件
Component({
options: {
multipleSlots: true // 在組件定義時的選項中啓用多slot支持
},
/**
* 組件的默認屬性列表
* 用於組件自定義設置
*/
properties: {
// 彈窗標題
title: { // 屬性名
type: String, // 類型(必填),目前接受的類型包括:String, Number, Boolean, Object, Array, null(表示任意類型)
value: '標題' // 屬性初始值(可選),如果未指定則會根據類型選擇一個
},
// 彈窗內容
content: {
type: String,
value: '彈窗內容'
},
// 彈窗取消按鈕文字
cancelText: {
type: String,
value: '取消'
},
// 彈窗確認按鈕文字
confirmText: {
type: String,
value: '確定'
},
// 彈窗是否顯示“取消”按鈕
isShowCancelBtn: {
type: Boolean,
value: false
}
},
/**
* 私有數據,組件的初始數據
* 可用於模版渲染
*/
data: {
// 彈窗顯示控制:默認不顯示
isShow: false,
updatePanelAnimationData: ''
},
/**
* 組件的方法列表
* 更新屬性和數據的方法與更新頁面數據的方法類似
*/
methods: {
/*
* 公有方法(父組件會調用)
*/
//隱藏彈框
hideDialog() {
this.leavePupAnimation();
},
//展示彈框
showDialog() {
this.goIntoPupAnimation();
},
// 彈窗淡入動畫設置
goIntoPupAnimation() {
// 第1步:創建動畫實例
let animation = wx.createAnimation({
duration: 500, //動畫時長
timingFunction: "linear", //線性
});
// 第2步:這個動畫實例賦給當前的動畫實例
this.animation = animation;
// 第3步:執行第一組動畫
animation.opacity(0).step();
// 第4步:導出動畫對象賦給數據對象儲存
this.setData({
updatePanelAnimationData: animation.export(),
isShow: true //顯示彈窗
})
// 第5步:設置定時器到指定時候後,執行第二組動畫
setTimeout(function() {
// 執行第二組動畫
animation.opacity(1).step();
// 給數據對象儲存的第一組動畫,更替爲執行完第二組動畫的動畫對象
this.setData({
updatePanelAnimationData: animation,
})
}.bind(this), 500)
},
// 彈窗淡出動畫設置
leavePupAnimation() {
// 第1步:創建動畫實例
let animation = wx.createAnimation({
duration: 500, //動畫時長
timingFunction: "linear", //線性
});
// 第2步:這個動畫實例賦給當前的動畫實例
this.animation = animation;
// 第3步:執行第一組動畫
animation.opacity(0).step();
// 第4步:導出動畫對象賦給數據對象儲存
this.setData({
updatePanelAnimationData: animation.export()
})
// 第5步:設置定時器到指定時候後,執行第二組動畫
setTimeout(function() {
// 執行第二組動畫
animation.opacity(0).step();
// 給數據對象儲存的第一組動畫,更替爲執行完第二組動畫的動畫對象
this.setData({
updatePanelAnimationData: animation,
isShow: false //隱藏彈窗
})
}.bind(this), 500)
},
/*
* 內部私有方法建議以下劃線開頭:子組件內調用
* triggerEvent 用於觸發事件
*/
_cancelEvent(e) {
//觸發點擊“取消”按鈕回調
console.log('子組件dialog.js——您點擊了“取消”按鈕');
console.log('取消按鈕信息:', e);
// 通過triggerEvent來給父組件傳遞信息的
this.triggerEvent("cancelEvent", '取消'); // 將子組件數據通過參數的形式傳遞給父組件,這裏是向父組件傳遞事件名,傳遞一個參數值('取消')給父組件
this.hideDialog(); //隱藏彈窗
},
_confirmEvent(e) {
//觸發點擊“確認”按鈕回調
console.log('子組件dialog.js——點擊了“確認”按鈕');
console.log('確認按鈕信息:', e);
this.triggerEvent("confirmEvent", '確認');
this.hideDialog(); //隱藏彈窗
}
}
})
父組件頁面引用子組件:
1、聲明引用子組件:
{
"usingComponents": {
"dialog": "/components/Dialog/dialog" //左邊是頁面使用組件名,類似:<dialog></dialog>;右邊是子組件路徑
}
}
2、頁面使用組件:
<!--index.wxml-->
<!-- 父組件頁面 -->
<view class="container">
<!-- 引用子組件 -->
<dialog id='dialog'
title='{{dialogData.title}}'
content='{{dialogData.content}}'
cancelText='{{dialogData.cancelText}}'
confirmText='{{dialogData.confirmText}}'
isShowCancelBtn='{{dialogData.isShowCancelBtn}}'
bind:cancelEvent="{{dialogData.cancelEvent}}"
bind:confirmEvent="{{dialogData.confirmEvent}}">
</dialog>
<!-- 以上內容備註:11/12行代碼:當子組件觸發某個事件時,給其添加綁定事件回調給父組件也觸發事件相應的事件處理,抒寫規範:bindmyevent="onMyEvent"或bind:myevent="onMyEvent"的形式。-->
<button type="primary" bindtap="showDialog"> ClickMe! </button>
</view>
3、初始化子組件數據:
//index.js
//獲取應用實例
const app = getApp()
Page({
data: {
dialogData: { //傳向子組件自定義的彈窗內容:默認
title: '溫馨提示', //標題
content: '恭喜你,學會了自定義組件咯', //內容
cancelText: '取消', //取消按鈕內容
confirmText: '確定', //確認按鈕內容,
isShowCancelBtn: false, //是否顯示“取消”按鈕,默認顯示
cancelEvent: '_cancelEvent', //綁定點擊取消按鈕後的事件
confirmEvent: '_confirmEvent', //綁定點擊確認按鈕後的事件
}
},
/**
* 生命週期函數--監聽頁面顯示
*/
onShow: function() {
//獲得dialog組件:初始化組件
this.dialog = this.selectComponent("#dialog"); //獲取子組件實例對象,這樣就可以直接訪問組件的任意數據和方法。
// 自定義初始化數據內容,會傳給子組件顯示(可以不設置,有默認值)
// this.setData({
// dialogData: { //傳向子組件自定義的彈窗內容:默認
// title: '溫馨提示', //標題
// content: '恭喜你,學會了自定義組件咯', //內容
// cancelText: '取消', //取消按鈕內容
// confirmText: '確定', //確認按鈕內容,
// isShowCancelBtn: true, //是否顯示“取消”按鈕,默認顯示
// cancelEvent: '_cancelEvent', //綁定點擊取消按鈕後的事件
// confirmEvent: '_confirmEvent', //綁定點擊確認按鈕後的事件
// }
// })
},
// 點擊顯示彈窗提示
showDialog() {
console.log('父組件——點擊顯示子組件彈窗操作');
this.dialog.showDialog(); //調用組件彈窗顯示方法:showDialog()
},
//取消事件
_cancelEvent(e) {
console.log('父組件index.js——你在子組件點擊“取消”按鈕,在這裏執行回調操作');
console.log('父組件index.js——取消事件——獲取子組件傳遞過來的值:', e);
},
//確認事件
_confirmEvent(e) {
console.log('父組件index.js——你在子組件點擊“確認”按鈕,在這裏執行回調操作');
console.log('父組件index.js——確認事件——獲取子組件傳遞過來的值:', e);
}
})
(三)實現原理
(四)參考文獻
可以根據這個示例,自定義很多自己想要的組件了,比如說根據這個組件彈窗寫一個仿微信小程序的消息提示框、表單信息框之類的等等,感謝閱讀。