基于confirm組件
使用微信開發(fā)者工具
最近在學(xué)習(xí)微信小程序,不止一個(gè)頁(yè)面有confirm衣撬,所以決定把他抽離成一個(gè)組件隘擎。剛好就涉及到了父子組件之間的通訊問(wèn)題殴穴。
如何創(chuàng)建組件,引入組件
創(chuàng)建組件
image
首先在components文件夾下新建g-confirm文件夾。右鍵點(diǎn)擊新建component货葬。會(huì)新建四個(gè)文件采幌。
image
因?yàn)槲募?nèi)有關(guān)于組件的配置問(wèn)題,所以不太建議新手自己手動(dòng)創(chuàng)建震桶。
引入組件
在pages/index文件夾下也就是主頁(yè)目錄下休傍,下打開index.json配置文件。
在usingComponents
配置下引入想使用的任何自定義組件
image
在index.wxml中引入組件
<!--index.wxml-->
<view class="container">
<text>這是在主頁(yè)內(nèi)</text>
<g-confirm></g-confirm>
</view>
成功引入自定義組件
image
confirm組件
需求: 點(diǎn)擊按鈕調(diào)出confirm,用戶輸入后獲取輸入的內(nèi)容. 因?yàn)榘裞onfirm抽離成組件,所以涉及到了組件之間的通信
點(diǎn)擊按鈕confirm出現(xiàn),選擇后confirm隱藏
使用visible的值控制confirm
index.wxml
<button bind:tap="click">添加任務(wù)</button>
<g-confirm visible="{{visible}}" bind:sureClick="sureClick" bind:cancelClick="cancelClick"></g-confirm>
// 使用visible組件,并將visible的值傳遞給confirm
// 監(jiān)聽子組件觸發(fā)的事件,并做出相應(yīng)
<view >用戶輸入的是--{{inputValue}}</view>
index.js
data;{
visible: false,
inputVale: ""
},
click(){
this.setData({
visible: true
})
},
sureClick(event){
this.setData({
visible: false
})
},
cancelClick(){
this.setData({
visible: false
})
}
// 當(dāng)子組件按鈕被點(diǎn)擊時(shí)觸發(fā),隱藏confirm
g-confirm.wxml
<view class="confirmWrapper" wx:if="{{visible}}">
// wx:if和v-if類似,只有值為true時(shí)才渲染
<view class="confirm">
<textarea class="input"></textarea>
<view class="actions">
//給按鈕綁定事件
<view class="sure" bind:tap="sureClick">確定</view>
<view class="cancel" bind:tap="cancelClick">取消</view>
</view>
</view>
</view>
g-confirm.js
// 接收參數(shù)
properties: {
visible: {
type: Boolean,
value: false
}
},
methods: {
sureClick() {
this.triggerEvent("sureClick",'按鈕被點(diǎn)擊');
// 微信小程序的事件中心,類似 emit()
// 觸發(fā)sureClick事件
},
cancelClick() {
this.triggerEvent("cancelClick");
}
}
監(jiān)聽用戶輸入的內(nèi)容,傳遞給父組件
用戶輸入完畢后,將用戶輸入的內(nèi)容展示到頁(yè)面
g-confirm.wxml
<textarea value="{{value}}" bind:input="watchInput"></textarea>
// 監(jiān)聽input輸入框,用戶輸入內(nèi)容改變都會(huì)觸發(fā)
g-confirm.js
data: {
value: ""
},
methods: {
watchInput(event) {
this.data.value = event.detail.value;
// input內(nèi)容每次變動(dòng),就把他存到data里
},
sureClick() {
this.triggerEvent("sureClick",this.data.value);
// 事件中心, 點(diǎn)擊確認(rèn)后將value傳遞給父組件
},
cancelClick() {
this.triggerEvent("cancelClick");
}
}
index.wxml
<g-confirm bind:sureClick="sureClick" bind:cancelClick="cancelClick" ></g-confirm>
<view >用戶輸入的是--{{inputValue}}</view>
// 綁定inputValue值
index.js
data: {
inputValue: ""
},
sureClick(event){
this.setData({
inputValue: event.detail
})
// 只有通過(guò)setData改變data的值,頁(yè)面內(nèi)容才會(huì)同步刷新
}