[微信小程序] 組件的引入與方法呼叫
可以將需要重複的區塊做成組件,組件一樣由 json、js、wxml、wxss 組成,但在設定檔 (json) 中設定 "component": true。並且 js 初始化是使用 Component,而非 Page。
引入的頁面在自己的 json 中聲明引入:
// page.json
"usingComponents": {
"componet-name": "componentPath"
}
之後就可以將組件作為一般的 tag 來使用:
// page.wxml <componet-name id="component-id"></componet-name>
透過 ID 的設置和存取,可以呼叫組件內的方法。
// page.js
onLoad: function (options) {
this.SelfComponent = this.selectComponent('#component-id');
this.SelfComponent.innerMethod();
},