微信小程序 Component構(gòu)造器

2022-04-25 11:44 更新

Component 構(gòu)造器

Component 構(gòu)造器可用于定義組件,調(diào)用 Component 構(gòu)造器時(shí)可以指定組件的屬性、數(shù)據(jù)、方法等。

詳細(xì)的參數(shù)含義和使用請參考 Component 參考文檔

Component({

  behaviors: [],

  properties: {
    myProperty: { // 屬性名
      type: String,
      value: ''
    },
    myProperty2: String // 簡化的定義方式
  },
  
  data: {}, // 私有數(shù)據(jù),可用于模板渲染

  lifetimes: {
    // 生命周期函數(shù),可以為函數(shù),或一個(gè)在methods段中定義的方法名
    attached: function () { },
    moved: function () { },
    detached: function () { },
  },

  // 生命周期函數(shù),可以為函數(shù),或一個(gè)在methods段中定義的方法名
  attached: function () { }, // 此處attached的聲明會(huì)被lifetimes字段中的聲明覆蓋
  ready: function() { },

  pageLifetimes: {
    // 組件所在頁面的生命周期函數(shù)
    show: function () { },
    hide: function () { },
    resize: function () { },
  },

  methods: {
    onMyButtonTap: function(){
      this.setData({
        // 更新屬性和數(shù)據(jù)的方法與更新頁面數(shù)據(jù)的方法類似
      })
    },
    // 內(nèi)部方法建議以下劃線開頭
    _myPrivateMethod: function(){
      // 這里將 data.A[0].B 設(shè)為 'myPrivateData'
      this.setData({
        'A[0].B': 'myPrivateData'
      })
    },
    _propertyChange: function(newVal, oldVal) {

    }
  }

})

使用 Component 構(gòu)造器構(gòu)造頁面

事實(shí)上,小程序的頁面也可以視為自定義組件。因而,頁面也可以使用 Component 構(gòu)造器構(gòu)造,擁有與普通組件一樣的定義段與實(shí)例方法。但此時(shí)要求對應(yīng) json 文件中包含 usingComponents 定義段。

此時(shí),組件的屬性可以用于接收頁面的參數(shù),如訪問頁面 /pages/index/index?paramA=123&paramB=xyz ,如果聲明有屬性 paramA 或 paramB ,則它們會(huì)被賦值為 123 或 xyz 。

頁面的生命周期方法(即 on 開頭的方法),應(yīng)寫在 methods 定義段中。

代碼示例:

{
  "usingComponents": {}
}
Component({

  properties: {
    paramA: Number,
    paramB: String,
  },

  methods: {
    onLoad: function() {
      this.data.paramA // 頁面參數(shù) paramA 的值
      this.data.paramB // 頁面參數(shù) paramB 的值
    }
  }

})

使用 Component 構(gòu)造器來構(gòu)造頁面的一個(gè)好處是可以使用 behaviors 來提取所有頁面中公用的代碼段。

例如,在所有頁面被創(chuàng)建和銷毀時(shí)都要執(zhí)行同一段代碼,就可以把這段代碼提取到 behaviors 中。

代碼示例:

// page-common-behavior.js
module.exports = Behavior({
  attached: function() {
    // 頁面創(chuàng)建時(shí)執(zhí)行
    console.info('Page loaded!')
  },
  detached: function() {
    // 頁面銷毀時(shí)執(zhí)行
    console.info('Page unloaded!')
  }
})
// 頁面 A
var pageCommonBehavior = require('./page-common-behavior')
Component({
  behaviors: [pageCommonBehavior],
  data: { /* ... */ },
  methods: { /* ... */ },
})
// 頁面 B
var pageCommonBehavior = require('./page-common-behavior')
Component({
  behaviors: [pageCommonBehavior],
  data: { /* ... */ },
  methods: { /* ... */ },
})


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)