QQ小程序 behaviors

2020-07-01 18:02 更新

定義和使用 behaviors

behaviors 是用于組件間代碼共享的特性,類似于一些編程語言中的“mixins”或“traits”。 每個 behavior 可以包含一組屬性、數(shù)據(jù)、生命周期函數(shù)和方法,組件引用它時(shí),它的屬性、數(shù)據(jù)和方法會被合并到組件中,生命周期函數(shù)也會在對應(yīng)時(shí)機(jī)被調(diào)用。每個組件可以引用多個 behavior。behavior 也可以引用其他 behaviorbehavior 需要使用 Behavior() 構(gòu)造器定義。

// my-behavior.js
module.exports = Behavior({
  behaviors: [],
  properties: {
    myBehaviorProperty: {
      type: String
    }
  },
  data: {
    myBehaviorData: {}
  },
  attached() {},
  methods: {
    myBehaviorMethod() {}
  }
})

組件引用時(shí),在 behaviors 定義段中將它們逐個列出即可。

組件引用時(shí),在 behaviors 定義段中將它們逐個列出即可。 代碼示例:

// my-component.js
const myBehavior = require('my-behavior')
Component({
  behaviors: [myBehavior],
  properties: {
    myProperty: {
      type: String
    }
  },
  data: {
    myData: {}
  },
  attached() {},
  methods: {
    myMethod() {}
  }
})
// my-component.js
const myBehavior = require('my-behavior')
Component({
  behaviors: [myBehavior],
  properties: {
    myProperty: {
      type: String
    }
  },
  data: {
    myData: {}
  },
  attached() {},
  methods: {
    myMethod() {}
  }
})

在上例中, my-component 組件定義中加入了 my-behavior ,而 my-behavior 中包含有 myBehaviorProperty 屬性、 myBehaviorData 數(shù)據(jù)字段、 myBehaviorMethod 方法和一個 attached 生命周期函數(shù)。這將使得 my-component 中最終包含 myBehaviorProperty 、 myProperty 兩個屬性, myBehaviorData 、 myData 兩個數(shù)據(jù)字段,和 myBehaviorMethod 、 myMethod 兩個方法。當(dāng)組件觸發(fā) attached 生命周期時(shí),會依次觸發(fā) my-behavior 中的 attached 生命周期函數(shù)和 my-component 中的 attached 生命周期函數(shù)。

字段的覆蓋和組合規(guī)則

組件和它引用的 behavior 中可以包含同名的字段,對這些字段的處理方法如下:

  • 如果有同名的屬性或方法,組件本身的屬性或方法會覆蓋 behavior 中的屬性或方法,如果引用了多個 behavior ,在定義段中靠后 behavior 中的屬性或方法會覆蓋靠前的屬性或方法;
  • 如果有同名的數(shù)據(jù)字段,如果數(shù)據(jù)是對象類型,會進(jìn)行對象合并,如果是非對象類型則會進(jìn)行相互覆蓋;
  • 生命周期函數(shù)不會相互覆蓋,而是在對應(yīng)觸發(fā)時(shí)機(jī)被逐個調(diào)用。如果同一個 behavior 被一個組件多次引用,它定義的生命周期函數(shù)只會被執(zhí)行一次。

內(nèi)置behaviors

自定義組件可以通過引用內(nèi)置的 behavior 來獲得內(nèi)置組件的一些行為。

Component({
  behaviors: ['qq://form-field']
})

在上例中, qq://form-field 代表一個內(nèi)置 behavior ,它使得這個自定義組件有類似于表單控件的行為。 內(nèi)置 behavior 往往會為組件添加一些屬性。在沒有特殊說明時(shí),組件可以覆蓋這些屬性來改變它的 type 或添加 observer 。

qq://form-field

使自定義組件有類似于表單控件的行為。 form 組件可以識別這些自定義組件,并在 submit 事件中返回組件的字段名及其對應(yīng)字段值。這將為它添加以下兩個屬性。

屬性名 類型 描述
name String 在表單中的字段名
value 任意 在表單中的字段值

qq://component-export

使自定義組件支持 export 定義段。這個定義段可以用于指定組件被 selectComponent 調(diào)用時(shí)的返回值。 未使用這個定義段時(shí), selectComponent 將返回自定義組件的 this (插件的自定義組件將返回 null )。使用這個定義段時(shí),將以這個定義段的函數(shù)返回值代替。

代碼示例:

// 自定義組件 my-component 內(nèi)部
Component({
  behaviors: ['qq://component-export'],
  export() {
    return {myField: 'myValue'}
  }
})

<!-- 使用自定義組件時(shí) -->
<my-component id="the-id" />

this.selectComponent('#the-id') // 等于 { myField: 'myValue' }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號