在寫小程序的時候,有時候頁面的內容過多,邏輯比較復雜,如果全部都寫在一個頁面的話,會比較繁雜,代碼可讀性比較差,也不易於后期代碼維護,這時候可以把里面某部分功能抽出來,單獨封裝為一個組件,也就是通常說的自定義組件,自定義組件類似於頁面,它有wxml
模版、wxss
樣式和js文件,然后在頁面中使用該自定義組件即可。
例如,我的自定義組件代碼結構是這樣的:
myComponent文件就是我所創的自定義組件,myComponent.wxml文件代碼為:
<view class="inner"> <Text>I am learning 微信小程序</Text> </view>
myComponent.js文件代碼為:
const app = getApp() Component({ properties: { // 這里定義了innerText屬性,屬性值可以在組件使用時指定 innerText: { type: String, // value: '', } }, data: { // 這里是一些組件內部數據 someData: {} }, methods: { customMethod(){ console.log('hello world! I am learning 微信小程序') } } })
myComponent.wxss部分代碼如下:
.inner{ color:red }
現在我要在pages/index文件中使用該自定義組件,該怎么做呢?
1、在myComponent.json文件中添加以下代碼:
{ "component": true }
2、在需要調用自定義組件的文件中,如pages/index文件需要調用自定義組件,那么則需要在pages/index/index.json文件中添加如下代碼:
{ "usingComponents": { "myComponent": "../../components/myComponent/myComponent" // 組件名以及組件所在路徑 } }
3、然后就可以在myComponent.wxml文件中使用該自定義組件了,
index.wxml文件代碼如下:
<view> <myComponent id="myComponent"></myComponent> </view>
此時調用自定義組件后,效果如下:
4、現在要調用自定義組件中的方法就可以這樣做,為了方便,這里我使用的是點擊按鈕調用事件,因此index.wxml文件代碼變為:
<view> <button bindtap="showComponent">組件調用</button> <myComponent id="myComponent"></myComponent> </view>
5、myComponent.js文件部分代碼為:
// pages/index/index.js Page({ /** * 頁面的初始數據 */ data: { }, /** * 生命周期函數--監聽頁面初次渲染完成 */ onReady: function () { // 頁面初次渲染完成后,使用選擇器選擇組件實例節點,返回匹配到組件實例對象 this.myComponent = this.selectComponent('#myComponent') }, /** * 生命周期函數--監聽頁面顯示 */ onShow: function () { }, /** * 生命周期函數--監聽頁面隱藏 */ onHide: function () { }, /** * 生命周期函數--監聽頁面卸載 */ onUnload: function () { }, showComponent: function () { let myComponent = this.myComponent myComponent.customMethod() // 調用自定義組件中的方法 } })
現在點擊按鈕后就可以調用自定義組件了。效果如下:
轉: https://www.cnblogs.com/jf-67/p/8709556.html