Mini Program Development Custom Components

Mini Program Development Custom Components

Dongguan applet develops custom components, creates custom components, and accepts a parameter of type Object. The generated component instance can be accessed through this in the component's methods, lifecycle functions, and property observers. Components contain some common properties and methods. Changes in property values ​​can be monitored using observers. Currently, this field is not recommended in the new version of the base library. Instead, use the observers field of the Component constructor, which is more powerful and has better performance.

Component(Object object)

Create a custom component that accepts an Object type parameter.

parameter

Object object

Definition segment type Required? describe Minimum version
properties Object Map no The external properties of a component are a mapping table from property names to property settings.
data Object no The internal data of the component, used together with properties for component template rendering
observers Object no Component data field listener, used to monitor changes in properties and data, see Data Listener 2.6.1
methods Object no Component methods, including event response functions and any custom methods. For the use of event response functions, see Inter-component communication and events.
behaviors String Array no Similar to mixins and traits, a mechanism for reusing code between components. See behaviors
created Function no Component lifecycle function - executed when the component instance is just created. Note that setData cannot be called at this time.
attached Function no Component lifecycle function - executed when the component instance enters the page node tree)
ready Function no Component lifecycle function - executed after component layout is completed)
moved Function no Component lifecycle function - executed when the component instance is moved to another location in the node tree)
detached Function no Component lifecycle function - executed when the component instance is removed from the page node tree)
relations Object no For the definition of inter-component relationships, see Inter-component relationships
externalClasses String Array no External style classes accepted by the component, see External style classes
options Object Map no Some options (the specific option settings will be involved when introducing related features in the document, which are not listed here for the time being)
lifetimes Object no Component life cycle declaration object, see Component life cycle 2.2.3
pageLifetimes Object no The life cycle declaration object of the page where the component is located, see Component Life Cycle 2.2.3
definitionFilter Function no Define segment filters for custom component extensions, see Custom Component Extensions 2.2.3

The generated component instance can be accessed through this in the component's methods, lifecycle functions, and property observers. Components contain some common properties and methods.

Property name type describe
is String The file path of the component
id String Node id
dataset String Node dataset
data Object Component data, including internal data and attribute values
properties Object Component data, including internal data and attribute values ​​(consistent with data)
Method Name parameter describe Minimum version
setData Object newData Set data and perform view layer rendering
hasBehavior Object behavior Checks whether the component has a behavior (all behaviors introduced directly or indirectly will be recursively checked)
triggerEvent String name, Object detail, Object options Trigger events, see Inter-component communication and events
createSelectorQuery Create a SelectorQuery object whose selector selection range is within this component instance
createIntersectionObserver Create an IntersectionObserver object with a selector scoped to this component instance.
selectComponent String selector Use the selector to select the component instance node and return the first matching component instance object (affected by wx://component-export)
selectAllComponents String selector Use the selector to select the component instance node and return an array of all matching component instance objects (affected by wx://component-export)
selectOwnerComponent Select the component instance where the current component node is located (i.e. the component's referrer), and return its component instance object (will be affected by wx://component-export) 2.8.2
getRelationNodes String relationKey Get all associated nodes corresponding to this relationship, see Relationships between components
groupSetData Function callback Execute callback immediately, and multiple setData will not trigger interface drawing (only required in some special scenarios, such as synchronizing interface drawing when different components setData at the same time) 2.4.0
getTabBar Returns the component instance of the custom-tab-bar of the current page. For details, see Customizing tabBar 2.6.2
getPageId Returns the page identifier (a string), which can be used to determine whether several custom component instances are on the same page 2.7.1
animate String selector, Array keyframes, Number duration, Function callback Execute keyframe animation, see Animation for details 2.9.0
clearAnimation String selector, Object options, Function callback Clear keyframe animation, see animation for details 2.9.0

Code example:

Preview the effect in the developer tools

 Component({
  behaviors: [],
  // Property definitions (see below for details)
  properties:
    myProperty: { // property name type: String,
      value: ''
    },
    myProperty2: String // simplified definition method },
  data: {}, // Private data, can be used for template rendering lifetimes: {
    // Lifecycle function, which can be a function or a method name defined in the methods section attached: function () { },
    moved: function () { },
    detached: function () { },
  },
  // Lifecycle function, which can be a function or a method name defined in the methods section attached: function () { }, // The declaration of attached here will be overwritten by the declaration in the lifetimes field ready: function() { },
  pageLifetimes: {
    // Life cycle function of the page where 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 the method of updating page data })
    },
    // Internal methods are recommended to start with an underscore _myPrivateMethod: function(){
      // Here data.A[0].B is set to 'myPrivateData'
      this.setData({
        'A[0].B': 'myPrivateData'
      })
    },
    _propertyChange: function(newVal, oldVal) {
    }
  }})

Note: In the properties definition section, the property name is written in camelCase (propertyName); in wxml, hyphens are used when specifying property values ​​(component-tag-name property-name="attr value"), and camelCase is used when applied to data binding (attr="").

Properties Definition

Definition segment type Required? describe Minimum version
type yes Type of property
optionalTypes Array no The type of the attribute (you can specify multiple) 2.6.5
value no Initial value of the property
observer Function no Callback function when the property value changes

Changes in property values ​​can be monitored using observers. Currently, this field is not recommended in the new version of the base library. Instead, use the observers field of the Component constructor, which is more powerful and has better performance.

Code example:

 Component({
  properties:
    min: {
      type: Number,
      value: 0
    },
    min: {
      type: Number,
      value: 0,
      observer: function(newVal, oldVal) {
        // Executed when the property value changes }
    },
    lastLeaf: {
      // This property can be one of the three types: Number, String, Boolean type: Number,
      optionalTypes: [String, Object],
      value: 0
    }
  }
})

The type of the property 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. Thus, when specifying an attribute value as a literal in WXML, the value can have an exact type, such as:

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

At this time, since the corresponding attribute of the custom component is specified as a Number type, min and max will be assigned 1 and 5 instead of "1" and "5", that is:

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

Bugs & Tips:

  • Use this.data to get internal data and property values; but modifying it directly will not apply the changes to the interface, and setData should be used to modify it.
  • Lifecycle functions cannot be accessed through this in component methods.
  • Attribute names should avoid starting with data, that is, do not name them in the form of dataXyz, because in WXML, data-xyz="" will be processed as a node dataset rather than a component attribute.
  • When a component is defined and used, the component's attribute names and data fields cannot conflict with each other (even though they are located in different definition sections).
  • Starting from the basic library 2.0.9, the attributes and data fields of object types can contain subfields of function types, that is, functions can be passed through the attribute fields of object types. Base libraries below this version do not support this feature.
  • Bug: Custom components in slots do not trigger the page lifecycle declared in pageLifetimes. This problem is fixed in 2.5.2.
  • bug: For properties of type Object or Array, if a subfield of the property value is changed through the component's own this.setData, the property observer will still be triggered, and the newVal received by the observer is the value of the changed subfield, oldVal is empty, and changedPath contains information about the field name of the subfield; it is currently recommended to use the observers definition segment instead.

<<:  Case analysis: How to make a user operation analysis report?

>>:  Traffic generation and promotion: How to find target users before promotion?

Recommend

2020 Pinduoduo entry process and operation promotion strategy!

Recently, everyone is basically staying at home, ...

Douyin Dou+ Super Detailed Advertising Skills Strategy

What exactly is DOU+? However, unlike information...

Product Operations: 10 Practical Strategies for Attracting New Users!

Nowadays, in an era where traffic is king, the co...

Operational skills of Alipay products!

It turns out that Alipay is not only a payment pr...

[Optimization Tips] Headline Information Flow: Do you know all these tips?

When I get old, my hair turns white. Information ...