【愚公系列】2022年04月 微信小程序-Behavior

121 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第9天,点击查看活动详情

一、Behavior

1.Behavior的定义

behaviors 是用于组件间代码共享的特性,类似于一些编程语言中的 “mixins” 或 “traits”。

每个 behavior 可以包含一组属性、数据、生命周期函数和方法。组件引用它时,它的属性、数据和方法会被合并到组件中,生命周期函数也会在对应时机被调用。 每个组件可以引用多个 behavior ,behavior 也可以引用其它 behavior 。

2.Behavior的属性

定义段类型是否必填描述
propertiesObject Map同组件的属性
dataObject同组件的数据
methodsObject同自定义组件的方法
behaviorsString Array引入其它的 behavior
createdFunction生命周期函数
attachedFunction生命周期函数
readyFunction生命周期函数
movedFunction生命周期函数
detachedFunction生命周期函数

3.使用

module.exports = Behavior({
  behaviors: [],
  properties: {
    myBehaviorProperty: {
      type: String
    }
  },
  data: {
    myBehaviorData: {}
  },
  attached: function(){},
  methods: {
    myBehaviorMethod: function(){}
  }
})
// my-component.js
var myBehavior = require('my-behavior')
Component({
  behaviors: [myBehavior],
  properties: {
    myProperty: {
      type: String
    }
  },
  data: {
    myData: 'my-component-data'
  },
  created: function () {
    console.log('[my-component] created')
  },
  attached: function () { 
    console.log('[my-component] attached')
  },
  ready: function () {
    console.log('[my-component] ready')
  },
  methods: {
    myMethod: function () {
      console.log('[my-component] log by myMethod')
    },
  }
})

注意点:Behavior创建事件会早于组件,所以组件的同名属性会覆盖Behavior

二、内置的Behavior

1.wx://form-field

使自定义组件有类似于表单控件的行为。 form 组件可以识别这些自定义组件,并在 submit 事件中返回组件的字段名及其对应字段值。

2.wx://form-field-group

使 form 组件可以识别到这个自定义组件内部的所有表单控件。

3.wx://form-field-button

使 form 组件可以识别到这个自定义组件内部的 button 。如果自定义组件内部有设置了 form-type 的 button ,它将被组件外的 form 接受。

4.wx://component-export

使自定义组件支持 export 定义段。这个定义段可以用于指定组件被 selectComponent 调用时的返回值。