小程序原生引入組件和調用組件的方法


看一下我的組件結構 components(被調用的組件) index(頁面組件)請忽略調圖片

 

 module文件就是我所創的自定義組件,module.wxml文件代碼為:

<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文件部分代碼為:

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()  // 調用自定義組件中的方法
 }
})

  最后的結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM