Skip to content

Custom Components

Component

Create a custom component that accepts an Object type parameter.

Parameter

Object object

definition segmentTypeIs it required?Description
propertiesObject MapNoThe external attributes of the component are a mapping table from attribute names to attribute settings
dataObjectNoThe internal data of the component, together with properties, is used for component template rendering
observersObjectNoComponent data field listener, used to listen to changes in properties and data, see Data listener
methodsObjectNoComponent methods, including event response functions and any custom methods. For the use of event response functions, see Inter-component communication and events
behaviorsString ArrayNoSimilar to the inter-component code reuse mechanism of mixins and traits, see behaviors
createdFunctionNoComponent lifecycle function - executed when the component instance is just created, note that setData cannot be called at this time
attachedFunctionNoExecuted when the component instance enters the page node tree
readyFunctionNoComponent lifecycle function - executed after component layout is completed
detachedFunctionNoComponent lifecycle function - executed when the component instance is removed from the page node tree
relationsObjectNoDefinition of inter-component relationships, see Inter-component relationships
externalClassesString ArrayNoExternal style classes accepted by components, see External style classes
optionsObject MapNoSome options (specific option settings will be involved when introducing related features in the document, which are not listed here for the time being)
lifetimesObjectNoComponent life cycle declaration object, see Component life cycle
pageLifetimesObjectNoLife cycle declaration object of the page where the component is located, see Component life cycle

The generated component instance can be accessed through this in the component's methods, life cycle functions, and properties observer. The component contains some common properties and methods

Property nameTypeDescription
isStringThe file path of the component
idStringNode id
datasetStringNode dataset
dataObjectComponent data, including internal data and attribute values
propertiesObjectThe file path of the component (Consistent with data)
MethodParameterDescription
setDataObject newDataSet data and perform view layer rendering
triggerEventString name, Object detail, Object optionsTrigger events, see Communication and events between components
createSelectorQuery-Create an SelectorQuery object, the selector selection range is within this component instance
createIntersectionObserver-Create an IntersectionObserver object, the selector selection range is within this component instance
selectComponentString selectorUse the selector to select the component instance node and return the first matched component instance object (will be affected by wx://component-export)
selectAllComponentsString selectorUse the selector to select the component instance node and return an array of all matched component instance objects (will be affected by wx://component-export)
selectownerComponentString selectorGet all associated nodes corresponding to this relationship, see
getRelationNodesString relationKeyGet all associated nodes corresponding to this relationship, see Inter-component relationships
hasBehaviorhasBehaviorCheck whether the component has behavior (all behaviors introduced directly or indirectly will be recursively checked during the check)

Sample code:

js
Component({
  behaviors: [],

  // Property definition (see below for details)
  properties: {
    myProperty: {
      // Attribute name
      type: String,
      value: "",
    },
    myProperty2: String, // Simplified definition
  },

  data: {}, // Private data, available for template rendering

  lifetimes: {
    // Life cycle function, can be a function, or a method name defined in the methods section
    attached: function () {},
    moved: function () {},
    detached: function () {},
  },

  // Life cycle function, can be a function, or a method name defined in the methods section
  attached: function () {}, // The attached declaration here is overwritten by the declaration in the lifetimes field
  ready: function () {},

  pageLifetimes: {
    // Life Cycle Function for the Page on which the component is located
    show: function () {},
    hide: function () {},
    resize: function () {},
  },

  methods: {
    onMyButtonTap: function () {
      this.setData({
        // The method of updating properties and data is similar to that of updating page data
      });
    },
    // The internal method recommends starting with an underscore
    _myPrivateMethod: function () {
      // Here will be data.A[0].B Set to 'myPrivateData'
      this.setData({
        "A[0].B": "myPrivateData",
      });
    },
    _propertyChange: function (newVal, oldVal) {},
  },
});

properties

relations definition sectionTypeIs it required?Description
type-YesProperty type
value-NoProperty initial value
observerFunctionNoCallback function when property value changes
Property value changes can be monitored using observer. Currently, this field is not recommended in the new version of the base library. Instead, the observers field of the Component constructor is used instead, which is more powerful and has better performance.

TIP

The type field in the definition section is a required item.

Sample code:

js
Component({
  properties: {
    min: {
      type: Number,
      value: 0
    },
    min: {
      type: Number,
      value: 0,
      observer: function(newVal, oldVal) {
        // When property values change
      }
    },
    lastLeaf: {
      // This property can be Number 、 String 、 Boolean One of three types.
      type: Number,
      optionalTypes: [String, Object],
      value: 0
    }
  }
})

The property type can be one of String, Number, Boolean, Object, Array, or null to indicate no type restriction.

In most cases, it is best to specify an exact type for a property. In this way, when specifying attribute values

js
<custom-comp min="1" max="5" />

At this time, since the corresponding attributes of the custom component are specified as Number type, min and max will be assigned 1 and 5, not '1' and '5', that is:

js
this.data.min === 1 // true
this.data.max === 5 // true

tips

  • Use this.data to obtain internal data and attribute values; but directly modifying it will not apply the changes to the interface, and setData should be used to modify it;
  • Use this.data to obtain internal data and attribute values; but directly modifying it will not apply the changes to the interface, and setData should be used to modify it;
  • Use this.data to obtain internal data and attribute values; but directly modifying it will not apply the changes to the interface, and setData should be used to modify it;
  • Use this.data to obtain internal data and attribute values; but directly modifying it will not apply the changes to the interface, and setData should be used to modify it;

Behavior

Register a behavior, accepting an Object type parameter.

Parameter

Object object

definition segmentTypeIs it required?Description
propertiesObject MapNoSame component attributes
dataObjectNoSame component data
methodsObjectNoSame custom component methods
behaviorsString ArrayNoSimilar to the inter-component code reuse mechanism of mixins and traits, see behaviors
createdFunctionNoComponent life cycle function-executed when the component instance is just created. Note that setData cannot be called at this time
attachedFunctionNoComponent life cycle function-executed when the component instance enters the page node tree
readyFunctionNoComponent life cycle function-executed after component layout is completed
detachedFunctionNoComponent life cycle function-executed when the component instance is removed from the page node tree
relationsObjectNoSimilar to the inter-component code reuse mechanism of mixins and traits, see Relationships between components
lifetimesObjectNoComponent life cycle declaration object, see Component Lifecycle
pageLifetimesObjectNoLife cycle declaration object of the page where the component is located, see Component Lifecycle

Code example:

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