微信小程序組件的引入和調用的方法
看一下我的組件結構 components(被調用的組件) index(頁面組件)請忽略調圖片
module文件就是我所創的自定義組件,module.wxml文件代碼為:
1 2 3 |
<view class = "inner" > <Text>I am learning 微信小程序</Text> </view> |
module.js文件代碼為:
const app = getApp() Component({ properties: { // 這里定義了innerText屬性,屬性值可以在組件使用時指定 innerText: { type: String, // value: '', } }, data: { // 這里是一些組件內部數據 someData: {} }, methods: { customMethod(){ console.log('hello world! I am learning 微信小程序') } } })
現在我要在pages/index文件中使用該自定義組件,該怎么做呢?
1、在module.json文件中添加以下代碼:
{ "component": true }
2、在需要調用自定義組件的文件中,如pages/index文件需要調用自定義組件,那么則需要在pages/index/index.json文件中添加如下代碼:
{ "usingComponents": { "module": "../../components/module/module" // 組件名以及組件所在路徑 } }
3、然后就可以在module.wxml文件中使用該自定義組件了,
index.wxml文件代碼如下:
<view> <module id="module"></module> </view>
此時調用自定義組件后,效果如下:
4、現在要調用自定義組件中的方法就可以這樣做,為了方便,這里我使用的是點擊按鈕調用事件,因此index.wxml文件代碼變為:
<view> <button bindtap="showComponent">組件調用</button> <module id="module"></module> </view>
5、index.js文件部分代碼為:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const app = getApp() import { Resume } from '../../request/api' const request = new Resume() Page({ data: { }, onLoad: function () { // request.testInitial({ 'name':'123' }).then(res=>{ // console.log(res) // }) }, onReady: function () { // 頁面初次渲染完成后,使用選擇器選擇組件實例節點,返回匹配到組件實例對象 this .module= this .selectComponent( '#module' ) }, showComponent: function () { let module= this .module module.customMethod() // 調用自定義組件中的方法 } }) |
最后的結果:
如果您的問題還未解決可以聯系站長付費協助。

有問題可以加入技術QQ群一起交流學習
本站vip會員 請加入無憂模板網 VIP群(50604020) PS:加入時備注用戶名或昵稱
普通注冊會員或訪客 請加入無憂模板網 技術交流群(50604130)
客服微信號:15898888535
聲明:本站所有文章資源內容,如無特殊說明或標注,均為采集網絡資源。如若內容侵犯了原著者的合法權益,可聯系站長刪除。