近期在做一個項目,小程序普通頁面調用引入組件裏面的方,網上看了很多資料,還是被粗心的自己給整哭了。所以做完項目記錄下:
一、demo結構
1>頁面index
2>自定義組件tx
二、如何定義一個組件
在tx.json中將component設置爲true,即
三、引入組件(在index頁面引入自定組件tx)
1>在index.json中進行組件聲明
2>在index頁面中以標籤的形式引入組件
四、在index頁面中調用組件tx中的方法
1>在<tx></tx>上定義節點id,id的名字隨便起,如:
<tx id="comp"></tx>
2>創建組件實例對象
this.compData=selectComponent("#comp");
3>在需要的地方調用組件的方法
this.compData.show();
五、具體代碼:
1>index頁面
index.wxml
<view class="indexView">
<view>index頁面</view>
<view class="btn" bindtap='click'>點我打印</view>
<tx id="comp"></tx>
</view>
index.wxss
.indexView{
display: flex;
flex-direction: column;
align-items: center;
}
.btn{
background-color:aquamarine;
color:#fff;
font-size:30rpx;
padding:10rpx 40rpx;
border-radius: 10rpx;
margin-top:50rpx;
margin-bottom: 50rpx;
}
index.js
Page({
onLoad: function(){
this.compData = this.selectComponent("#comp")
},
click: function(){
this.compData.show();
}
})
說明:調用數據的話直接:this.compData.data.名字
index.json
{
"usingComponents": {
"tx":"/pages/tx/tx"
}
}
2>tx組件
tx.wxml
<view>組件頁</view>
tx.js
Component({
methods:{
show: function(){
console.log("show........")
}
}
})
tx.json
{
"component":true
}
六、點擊按鈕結果
輸出:show........
說明與延伸:1>組件實例對象在頁面生命週期函數中初始化或在需要使用的地方(index.js中的click函數中)初始化都ok!
2>把index頁面改成組件也是這樣調用(父組件調用子組件中的方法),
只需將index頁面進行一個簡單的調整,在index.json中多加一個 "component":true
即如下:
然後將index.js中的page替換成Component,click方法放在methods中即可:
最後輸出:show........
說明父組件調用子組件方法成功~
重點!!!
1》通過selectComponent不僅可以調用子組件的方法,還可以調用子組件內的任意數據!
2》子組件調用父組件裏的方法與子組件向父組件傳值一個原理,通過triggerEvent,所以說子組件調用父組件方法的同時也可以向父組件傳值》
3》小程序自定義組件間傳值可點此:組件間傳值
以上是父組件調用子組件的方法,下面進行一個補充,子組件調用父組件中的方法!
父組件index
index.wxml
<view class="indexView">
<son bindtransfer="slow"></son>
</view>
index.js
Component({
methods:{
slow: function(e){
console.log("我是父組件中的slow")
}
}
})
子組件:
son.wxml
<view bindtap="clicks">點我調用父組件的方法</view>
son.js
Component({
methods:{
clicks: function(){
this.triggerEvent("transfer")
}
}
})
最終的結果: