# Custom Components

# 1. Component Templates and Styles

Similar to pages, custom components have their own FXML templates and FTSS styles.

# 1.1 Component Template

The syntax for component templates is the same as that of page templates. The node tree generated by combining the component template with the component data will be inserted at the location where the component is referenced.

A <slot> node can be provided in the component template to carry child nodes provided when the component is referenced.

Code Example

<!-- Component Template -->
<view class="wrapper">
  <view>This is the internal node of the component</view>
  <slot></slot>
</view>
<!-- Page template referencing the component -->
<view>
  <component-tag-name>
    <!-- This content will be placed in the component's <slot> position -->
    <view>This is the content inserted into the component's slot</view>
  </component-tag-name>
</view>

Note

Custom components and their corresponding node names referenced in the template must be explicitly defined in the JSON file; otherwise, they will be treated as meaningless nodes. Additionally, node names can also be declared as abstract nodes.

# 1.2 Template Data Binding

Similar to regular FXML templates, data binding can be used to pass dynamic data to the properties of child components.

Code Example

<!-- Page template referencing the component -->
<view>
  <component-tag-name prop-a="{{dataFieldA}}" prop-b="{{dataFieldB}}">
    <!-- This content will be placed in the component's <slot> position -->
    <view>This is the content inserted into the component's slot</view>
  </component-tag-name>
</view>

In the above example, the component's properties propA and propB will receive the data passed from the page. The page can use setData to change the bound data fields.

Note

Such data binding can only pass JSON-compatible data. Starting from Base Library version 2.0.9, functions can also be included in the data (but these functions cannot be directly called in FXML; they can only be passed to child components).

# 1.3 Component FXML Slots

The FXML of a component can include a slot node to carry the FXML structure provided by the component user.

By default, a component's FXML can only have one slot. To use multiple slots, you need to declare it in the component's JavaScript.

Component({
  options: {
    multipleSlots: true // Enable multi-slot support in the component definition options
  },
  properties: { /* ... */ },
  methods: { /* ... */ }
})

At this point, multiple slots can be used in the component's FXML, differentiated by different name attributes.

<!-- Component Template -->
<view class="wrapper">
  <slot name="before"></slot>
  <view>This is the internal detail of the component</view>
  <slot name="after"></slot>
</view>

When using it, use the slot attribute to insert nodes into different slots.

<!-- Page template referencing the component -->
<view>
  <component-tag-name>
    <!-- This content will be placed in the component's <slot name="before"> position -->
    <view slot="before">This is the content inserted into the component's slot name="before"</view>
    <!-- This content will be placed in the component's <slot name="after"> position -->
    <view slot="after">This is the content inserted into the component's slot name="after"</view>
  </component-tag-name>
</view>

# 1.4 Component Styles

The styles in the component's FTSS file only apply to the nodes within the component's FXML. When writing component styles, note the following:

  • Components and pages referencing components cannot use ID selectors (#a), attribute selectors ([a]), or tag name selectors. Use class selectors instead.
  • Using descendant selectors (.a .b) in components and pages referencing components may lead to unexpected behavior in some extreme cases. If encountered, avoid using them.
  • Child element selectors (.a>.b) can only be used between view components and their child nodes. Using them for other components may cause unexpected issues.
  • Inherited styles, such as font and color, will be inherited from outside the component into the component.
  • Except for inherited styles, styles in app.ftss and the page containing the component will not affect custom components (unless the component's style isolation option is changed).
  • #a { } /* Cannot be used in components */
  • [a] { } /* Cannot be used in components */
  • button { } /* Cannot be used in components */
  • .a > .b { } /* Will only work if .a is a view component node */ Additionally, components can specify default styles for their nodes using the :host selector.

Code Example

/* Component custom-component.ftss */
:host {
  color: yellow;
}
<!-- Page's fxml -->
<custom-component>This text is yellow</custom-component>

# 1.5 Component Style Isolation

By default, a custom component's styles are only affected by its own FTSS. Unless one of the following two cases applies:

  1. If tag name selectors (or some other special selectors) are used in app.ftss or the page's FTSS to directly specify styles, these selectors will affect the page and all components. This practice is generally not recommended.
  2. Specify a special style isolation option styleIsolation.
Component({
  options: {
    styleIsolation: 'isolated'
  }
})

The styleIsolation option has been supported since Base Library version 1.1.7. It supports the following values:

  • isolated: Enables style isolation. Styles specified with class inside and outside the custom component will not affect each other (default in most cases).
  • apply-shared: Styles from the page's FTSS will affect the custom component, but styles specified in the custom component's FTSS will not affect the page.
  • shared: Styles from the page's FTSS will affect the custom component, and styles specified in the custom component's FTSS will also affect the page and other custom components with apply-shared or shared set. When using the latter two, be sure to pay attention to the mutual influence of styles between components.

If this Component constructor is used to construct a page, the default value is shared. Additionally, starting from Mini-Program Base Library version 1.1.7, the addGlobalClass option is supported, which can be set in the options of the Component.

This option is equivalent to setting styleIsolation: apply-shared, but this option will become invalid after setting the styleIsolation option.

Code Example

/* Component custom-component.js */
Component({
  options: {
    addGlobalClass: true,
  }
})
<!-- Component custom-component.fxml -->
<text class="red-text">The color of this text is determined by the styles defined in `app.ftss` and the page's `ftss`</text>
/* app.ftss */
.red-text {
  color: red;
}

# 1.6 External Style Classes

Supported from Base Library 1.1.7; compatibility handling is required for lower versions.

Sometimes, a component may want to accept externally passed style classes. In this case, you can define several external style classes in the Component using the externalClasses definition section.

This feature can be used to implement functionality similar to the hover-class attribute of the view component: the page can provide a style class assigned to view's hover-class, and this style class is written in the page rather than in the implementation of the view component.

Note

When using both regular style classes and external style classes on the same node, the priority between the two classes is undefined, so it's best to avoid this situation.

Code Example

/* Component custom-component.js */
Component({
  externalClasses: ['my-class']
})
<!-- Component custom-component.fxml -->
<custom-component class="my-class">The color of this text is determined by the class outside the component</custom-component>

This way, users of the component can specify the corresponding class for this style class, just like using regular attributes, and can specify multiple corresponding classes.

Code Example

<!-- Page's fxml -->
<custom-component my-class="red-text large-text" />
.red-text {
  color: red;
}
.large-text {
  font-size: 1.5em;
}

# 2. Component Constructor

The Component constructor can be used to define components. When calling the Component constructor, you can specify the component's properties, data, methods, etc.

For detailed parameter meanings and usage, please refer to the Component reference documentation.

Component({

  behaviors: [],

  properties: {
    myProperty: { // Property name
      type: String,
      value: ''
    },
    myProperty2: String // Simplified definition method
  },
  
  data: {}, // Private data, can be used for template rendering

  lifetimes: {
    // Lifecycle functions, can be functions or method names defined in the methods section
    attached: function () { },
    detached: function () { },
  },

  // Lifecycle functions, can be functions or method names defined in the methods section
  attached: function () { }, // The declaration here will be overridden by the declaration in the lifetimes field
  ready: function() { },

  methods: {
    onMyButtonTap: function(){
      this.setData({
        // Method to update properties and data, similar to updating page data
      })
    },
    // Internal methods are recommended to start with an underscore
    _myPrivateMethod: function(){
      // Here, set `data.A[0].B` to 'myPrivateData'
      this.setData({
        'A[0].B': 'myPrivateData'
      })
    },
    _propertyChange: function(newVal, oldVal) {

    }
  }

})

# 2.1 Using the Component Constructor to Construct Pages

In fact, Mini-Program pages can also be considered as custom components. Therefore, pages can also be constructed using the Component constructor, having the same definition sections and instance methods as regular components. However, this requires that the corresponding JSON file contains the usingComponents definition section.

At this point, the component's properties can be used to receive page parameters. For example, when accessing the page /pages/index/index?paramA=123&paramB=xyz, if properties paramA or paramB are declared, they will be assigned values of 123 or xyz.

Page lifecycle methods (i.e., methods starting with on) should be written in the methods definition section.

Code Example

{
  "usingComponents": {}
}
Component({

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

  methods: {
    onLoad: function() {
      this.data.paramA // Value of the page parameter paramA
      this.data.paramB // Value of the page parameter paramB
    }
  }

})

One advantage of using the Component constructor to construct pages is that behaviors can be used to extract common code segments from all pages. For example, if the same piece of code needs to be executed when all pages are created and destroyed, this code can be extracted into behaviors.​

Code Example

// page-common-behavior.js
module.exports = Behavior({
  attached: function() {
    // Executed when the page is created
    console.info('Page loaded!')
  },
  detached: function() {
    // Executed when the page is destroyed
    console.info('Page unloaded!')
  }
})
// Page A
var pageCommonBehavior = require('./page-common-behavior')
Component({
  behaviors: [pageCommonBehavior],
  data: { /* ... */ },
  methods: { /* ... */ },
})
// Page B
var pageCommonBehavior = require('./page-common-behavior')
Component({
  behaviors: [pageCommonBehavior],
  data: { /* ... */ },
  methods: { /* ... */ },
})

# 2.2 Communication and Events Between Components

# 2.2.1 Communication Between Components

The basic communication methods between components include the following:

  • FXML Data Binding: Used for setting data to specific properties of child components from parent components, only JSON-compatible data can be set (starting from Base Library version 1.0.0, functions can also be included in the data).
  • Events: Used for child components to pass data to parent components, any data can be passed.
  • If the above two methods are insufficient, the parent component can also obtain the child component instance object through the this.selectComponent method, allowing direct access to any data and methods of the component.

# 2.2.2 Listening to Events

The event system is one of the main ways of communication between components. Custom components can trigger arbitrary events, and the referencing page can listen to these events.

The method for listening to custom component events is exactly the same as listening to basic component events:​

Code Example

<!-- When the custom component triggers the "myevent" event, call the "onMyEvent" method -->
<component-tag-name bindmyevent="onMyEvent" />
<!-- Or it can be written as -->
<component-tag-name bind:myevent="onMyEvent" />
Page({
  onMyEvent: function(e){
    e.detail // The detail object provided when the custom component triggers the event
  }
})

# 2.2.3 Triggering Events

When a custom component triggers an event, the triggerEvent method must be used, specifying the event name, detail object, and event options:

<!-- In the custom component -->
<button bindtap="onTap">Clicking this button will trigger the "myevent" event</button>
Component({
  properties: {},
  methods: {
    onTap: function(){
      var myEventDetail = {} // Detail object, provided to the event listener function
      var myEventOption = {} // Options for triggering the event
      this.triggerEvent('myevent', myEventDetail, myEventOption)
    }
  }
})

The options for triggering events include:

Option Name Type Required Default Value Description
bubbles Boolean No false Whether the event bubbles
composed Boolean No false Whether the event can cross component boundaries; if false, the event will only trigger on the node tree of the referencing component and will not enter any other component's internals
capturePhase Boolean No false Whether the event has a capture phase
// Page page.FXML
<another-component bindcustomevent="pageEventListener1">
  <my-component bindcustomevent="pageEventListener2"></my-component>
</another-component>
// Component another-component.FXML
<view bindcustomevent="anotherEventListener">
  <slot />
</view>
// Component my-component.FXML
<view bindcustomevent="myEventListener">
  <slot />
</view>
// Component my-component.js
Component({
  methods: {
    onTap: function(){
      this.triggerEvent('customevent', {}) // Only triggers pageEventListener2
      this.triggerEvent('customevent', {}, { bubbles: true }) // Triggers pageEventListener2, then pageEventListener1 in sequence
      this.triggerEvent('customevent', {}, { bubbles: true, composed: true }) // Triggers pageEventListener2, anotherEventListener, then pageEventListener1 in sequence
    }
  }
})

# 2.2.4 Getting Component Instances

In the parent component, you can call this.selectComponent to get the instance object of the child component (custom components from plugins will return null).

When calling, you need to pass in a matching selector, such as: this.selectComponent(".my-component").

// Parent component
Page({
  data: {},
  getChildComponent: function () {
    const child = this.selectComponent('.my-component');
    console.log(child)
  }
})

In the above example, the parent component will get the instance object of the child component with the class my-component, which is the this of the child component.

Custom components can support the export definition segment, which can be used to specify the return value when the component is called by selectComponent.​

Code Example

// Inside the custom component my-component
Component({
  behaviors: ['wx://component-export'],
  export() {
    return { myField: 'myValue' }
  }
})
<!-- When using the custom component -->
<my-component id="the-id" />
// Parent component call
const child = this.selectComponent('#the-id') // Equals { myField: 'myValue' }

In the above example, when the parent component gets the instance of the child component with the id the-id, what it gets is the object { myField: 'myValue' }.

# 2.3 Component Lifecycle

The lifecycle of a component refers to some functions of the component itself, which are automatically triggered at special time points or when encountering certain framework events.

Among them, the most important lifecycles are created, attached, and detached, covering the major time points in the life process of a component instance.

  • When the component instance is just created, the created lifecycle is triggered. At this point, the component data this.data is the data data defined in the Component constructor. At this time, setData cannot be called. Generally, this lifecycle should only be used to add some custom property fields to the component this.
  • After the component is fully initialized and enters the page node tree, the attached lifecycle is triggered. At this point, this.data has been initialized to the current value of the component. This lifecycle is very useful, and most initialization work can be done at this time.
  • When the component leaves the page node tree, the detached lifecycle is triggered. When exiting a page, if the component is still in the page node tree, detached will be triggered.

# 2.3.1 Defining Lifecycle Methods

Lifecycle methods can be directly defined in the first-level parameter of the Component constructor.

Starting from Mini-Program Base Library version 1.0.2, the component's lifecycle can also be declared in the lifetimes field (which has the highest priority).

Code Example

Component({
  lifetimes: {
    attached: function() {
      // Executed when the component instance enters the page node tree
    },
    detached: function() {
      // Executed when the component instance is removed from the page node tree
    },
  },
  // The following is the old-style definition, which maintains compatibility with base library versions <1.0.2
  attached: function() {
    // Executed when the component instance enters the page node tree
  },
  detached: function() {
    // Executed when the component instance is removed from the page node tree
  },
  // ...
})

Lifecycle methods can also be written in behaviors, and they will not override lifecycle methods with the same name in other behaviors. However, note that if a component references the same behavior multiple times directly or indirectly, the lifecycle functions in this behavior will only execute once during a single execution timing.​

The available lifecycles are shown in the table below:

Lifecycle Parameters Description Minimum Version
created None Executed when the component instance is just created 1.0.0
attached None Executed when the component instance enters the page node tree 1.0.0
ready None Executed after the component layout in the View Layer is completed 1.0.0
detached None Executed when the component instance is removed from the page node tree 1.0.0
error Object Error Executed whenever a component method throws an error 2.1.7

# 2.4 Behaviors

Behaviors are features used for code sharing between components, similar to "mixins" or "traits" in some programming languages.

Each behavior can contain a set of properties, data, lifecycle functions, and methods. When a component references it, its properties, data, and methods are merged into the component, and lifecycle functions are called at the corresponding time. Each component can reference multiple behaviors, and behaviors can also reference other behaviors.

# 2.4.1 Usage in Components

When referencing components, simply list them one by one in the behaviors definition section.​

Code Example

// my-behavior.js

module.exports = Behavior({
  behaviors: [],
  properties: {
    myBehaviorProperty: {
      type: String
    }
  },
  data: {
    myBehaviorData: 'my-behavior-data'
  },
  created: function () {
    console.log('[my-behavior] created')
  },
  attached: function () {
    console.log('[my-behavior] attached')
  },
  ready: function () {
    console.log('[my-behavior] ready')
  },

  methods: {
    myBehaviorMethod: function () {
      console.log('[my-behavior] log by myBehaviorMehtod')
    },
  }
})
// 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')
    },
  }
})

In the above example, my-behavior is added to the definition of the my-component component, and the structure of my-behavior is:

  • Property: myBehaviorProperty
  • Data Field: myBehaviorData
  • Method: myBehaviorMethod
  • Lifecycle Functions: attached, created, ready

This will make the final structure of my-component as follows:

  • Properties: myBehaviorProperty, myProperty
  • Data Fields: myBehaviorData, myData
  • Methods: myBehaviorMethod, myMethod
  • Lifecycle Functions: attached, created, ready

When the component triggers its lifecycle, the execution order of the lifecycle functions in the example above is:

  1. [my-behavior] created
  2. [my-component] created
  3. [my-behavior] attached
  4. [my-component] attached
  5. [my-behavior] ready
  6. [my-component] ready

For detailed rules, refer to the Overriding and Combination Rules for Same-Named Fields.

# 2.4.2 Overriding and Combination Rules for Same-Named Fields

A component and the behavior it references can contain fields with the same name. The handling methods for these fields are as follows:

  • If there are properties (properties) or methods (methods) with the same name:
    1. If the component itself has this property or method, the component's property or method will override the one with the same name in the behavior;
    2. If the component itself does not have this property or method, the property or method of the behavior defined later in the component’s behaviors field will override the earlier one with the same name;
    3. Based on point 2, if there is a nested reference to behavior, the rule is: parent behavior overrides the child behavior's same-named properties or methods.
  • If there are data fields (data) with the same name:
    • If the same-named data fields are all object types, they will be merged;
    • In other cases, data overriding occurs, following the overriding rule: component > parent behavior > child behavior, and later-defined behavior > earlier-defined behavior (higher priority overrides lower priority, with the highest being the top priority).
  • Lifecycle functions do not override each other but are called sequentially at their respective triggering times:
    • For different lifecycle functions, the execution order of the component lifecycle functions is followed;
    • For the same type of lifecycle function, the following rules apply:
      • Behavior executes before the component;
      • Child behavior executes before parent behavior;
      • Earlier-defined behavior executes before later-defined behavior;
    • If the same behavior is referenced multiple times by a component, the lifecycle function it defines will only be executed once.

# 2.4.3 Built-in Behaviors

Custom components can obtain some behaviors of built-in components by referencing built-in behaviors.

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

In the example above, wx://form-field represents a built-in behavior that makes this custom component behave like a form control.

Built-in behaviors often add some properties to the component. Unless otherwise specified, the component can override these properties to change their type or add an observer.

# wx://form-field

Makes the custom component behave like a form control. The form component can recognize these custom components and return the component's field name and corresponding field value in the submit event.

# wx://form-field-group

Allows the form component to recognize all form controls inside this custom component.

# wx://form-field-button

Allows the form component to recognize buttons inside this custom component. If a button inside the custom component has form-type set, it will be accepted by the form outside the component.

# wx://component-export

Enables the custom component to support the export definition segment. This definition segment can be used to specify the return value when the component is called by selectComponent.

# 2.5 Component Relationships

# 2.5.1 Defining and Using Component Relationships

Sometimes you need to implement such components:

<custom-ul>
  <custom-li> item 1 </custom-li>
  <custom-li> item 2 </custom-li>
</custom-ul>

In this example, both custom-ul and custom-li are custom components that have relationships with each other, and communication between them can be complex. At this time, adding a relations definition segment during component definition can solve this problem.

Example Code

// path/to/custom-ul.js
Component({
  relations: {
    './custom-li': {
      type: 'child', // The target node associated should be a child node
      linked: function(target) {
        // Executed every time a custom-li is inserted; target is the instance object of that node, triggered after the node's attached lifecycle
      },
      linkChanged: function(target) {
        // Executed every time a custom-li is moved; target is the instance object of that node, triggered after the node's moved lifecycle
      },
      unlinked: function(target) {
        // Executed every time a custom-li is removed; target is the instance object of that node, triggered after the node's detached lifecycle
      }
    }
  },
  methods: {
    _getAllLi: function(){
      // Use getRelationNodes to obtain an array of nodes containing all associated custom-li instances, which are ordered
      var nodes = this.getRelationNodes('path/to/custom-li')
    }
  },
  ready: function(){
    this._getAllLi()
  }
})
// path/to/custom-li.js
Component({
  relations: {
    './custom-ul': {
      type: 'parent', // The target node associated should be a parent node
      linked: function(target) {
        // Executed every time it is inserted into custom-ul; target is the instance object of the custom-ul node, triggered after the attached lifecycle
      },
      linkChanged: function(target) {
        // Executed every time it is moved; target is the instance object of the custom-ul node, triggered after the moved lifecycle
      },
      unlinked: function(target) {
        // Executed every time it is removed; target is the instance object of the custom-ul node, triggered after the detached lifecycle
      }
    }
  }
})

Note

The relations definition must be added to both component definitions; otherwise, it will not take effect.

# 2.5.2 Associating a Category of Components

Sometimes, you need to associate a category of components, such as:

<custom-form>
  <view>
    input
    <custom-input></custom-input>
  </view>
  <custom-submit> submit </custom-submit>
</custom-form>

The custom-form component wants to associate with both custom-input and custom-submit components. At this time, if these two components share the same behavior:

// path/to/custom-form-controls.js
module.exports = Behavior({
  // ...
})
// path/to/custom-input.js
var customFormControls = require('./custom-form-controls')
Component({
  behaviors: [customFormControls],
  relations: {
    './custom-form': {
      type: 'ancestor', // The target node associated should be an ancestor node
    }
  }
})
// path/to/custom-submit.js
var customFormControls = require('./custom-form-controls')
Component({
  behaviors: [customFormControls],
  relations: {
    './custom-form': {
      type: 'ancestor', // The target node associated should be an ancestor node
    }
  }
})

Then, in the relations relationship definition, this behavior can be used instead of the component path as the target node for association:

// path/to/custom-form.js
var customFormControls = require('./custom-form-controls')
Component({
  relations: {
    'customFormControls': {
      type: 'descendant', // The target node associated should be a descendant node
      target: customFormControls
    }
  }
})

# 2.5.3 Relations Definition Segment

The relations definition segment contains the target component path and its corresponding options. The available options are shown in the table below.

Option Type Required Description
type String Yes The relative relationship of the target component. Possible values are parent, child, ancestor, descendant
linked Function No Relationship lifecycle function, triggered when the relationship is established in the page node tree, after the component's attached lifecycle
linkChanged Function No Relationship lifecycle function, triggered when the relationship changes in the page node tree, after the component's moved lifecycle
unlinked Function No Relationship lifecycle function, triggered when the relationship is removed from the page node tree, after the component's detached lifecycle
target String No If this is set, it indicates the behavior that the associated target node should have. All component nodes with this behavior will be associated

# 2.6 Data Observers

Data observers can be used to listen and respond to changes in any properties and data fields. Supported from Mini-Program Base Library version 2.0.11 onwards.

# 2.6.1 Using Data Observers

Sometimes, operations need to be performed when certain data fields are set via setData.

For example, this.data.sum should always be the sum of this.data.numberA and this.data.numberB. In this case, a data observer can be used to implement it as follows.

Component({
  attached: function() {
    this.setData({
      numberA: 1,
      numberB: 2,
    })
  },
  observers: {
    'numberA, numberB': function(numberA, numberB) {
      // This function is executed when numberA or numberB is set
      this.setData({
        sum: numberA + numberB
      })
    }
  }
})

# 2.6.2 Observer Field Syntax

Data observers can listen to changes in properties or internal data fields and can listen to multiple fields simultaneously. Each observer is triggered at most once per setData.

Additionally, observers can listen to sub-data fields, as shown in the example below.

Component({
  observers: {
    'some.subfield': function(subfield) {
      // Triggered when `setData` sets `this.data.some.subfield`
      // (Also triggered when `setData` sets `this.data.some`)
      subfield === this.data.some.subfield
    },
    'arr[12]': function(arr12) {
      // Triggered when `setData` sets `this.data.arr[12]`
      // (Also triggered when `setData` sets `this.data.arr`)
      arr12 === this.data.arr[12]
    },
  }
})

If you need to listen to changes in all sub-data fields, you can use the wildcard **.

Component({
  observers: {
    'some.field.**': function(field) {
      // Triggered when `setData` sets `this.data.some.field` itself or any of its sub-data fields
      // (Also triggered when `setData` sets `this.data.some`)
      field === this.data.some.field
    },
  },
  attached: function() {
    // This will trigger the observer above
    this.setData({
      'some.field': { /* ... */ }
    })
    // This will also trigger the observer above
    this.setData({
      'some.field.xxx': { /* ... */ }
    })
    // This will still trigger the observer above
    this.setData({
      'some': { /* ... */ }
    })
  }
})

Specifically, using just the wildcard ** can listen to all setData.

Component({
  observers: {
    '**': function() {
      // Triggered on every `setData`
    },
  },
})

Tip

  • Data observers listen to data fields involved in setData, even if the values of these data fields have not changed, the data observer will still be triggered.
  • If setData is used within the data observer function to set the data field it listens to, it may cause an infinite loop, so special attention is needed.

# 2.7 Pure Data Fields

Pure data fields are data fields in data that are not used for UI rendering and can be used to improve page update performance.

# Pure Data Fields in Component Data

In some cases, certain fields in data (including those set via setData) are neither displayed on the interface nor passed to other components, but are only used internally within the current component.

At this time, such data fields can be designated as "pure data fields". They will only be recorded in this.data and will not participate in any UI rendering process, which helps improve page update performance.

To designate "pure data fields", specify pureDataPattern as a regular expression in the options definition segment of the Component constructor. Fields whose names match this regular expression will become pure data fields. Code example:

Component({
  options: {
    pureDataPattern: /^_/ // Specifies all data fields starting with _ as pure data fields
  },
  data: {
    a: true, // Normal data field
    _b: true, // Pure data field
  },
  methods: {
    myMethod() {
      this.data._b // Pure data fields can be accessed in this.data
      this.setData({
        c: true, // Normal data field
        _d: true, // Pure data field
      })
    }
  }
})

The pure data fields in the above component will not be applied to FXML:

<view wx:if="{{a}}"> This line will be displayed </view>
<view wx:if="{{_b}}"> This line will not be displayed </view>

# Pure Data Fields in Component Properties

Properties can also be designated as pure data fields (following the regular expression of pureDataPattern).

Pure data fields in properties can receive externally passed property values like normal properties, but they cannot be directly used in the component's own FXML.

Code example:

Component({
  options: {
    pureDataPattern: /^_/
  },
  properties: {
    a: Boolean,
    _b: {
      type: Boolean,
      observer() {
        // Do not do this! This observer will never be triggered
      }
    },
  }
})

Note: The property observer for pure data fields will never trigger! If you want to listen for changes in property values, use a data listener instead.

You can also configure pureDataPattern in the JSON file of the page or custom component (so there is no need to configure it again in the options of the JS file). In this case, its value should be written as a string:

{
  "pureDataPattern": "^_"
}

# Using Data Listeners to Listen to Pure Data Fields

Data listeners can be used to listen to pure data fields (just like normal data fields). This way, you can change the interface by listening and responding to changes in pure data fields.

The following example is a custom component that converts JavaScript timestamps into readable time.

Preview the effect in Developer Tools

Code example:

Component({
  options: {
    pureDataPattern: /^timestamp$/ // Designate the timestamp property as a pure data field
  },
  properties: {
    timestamp: Number,
  },
  observers: {
    timestamp: function () {
      // When timestamp is set, display it as a readable time string
      var timeString = new Date(this.data.timestamp).toLocaleString()
      this.setData({
        timeString: timeString
      })
    }
  }
})

<view>{{timeString}}</view>

# 2.8 Abstract Nodes

# Using Abstract Nodes in Components

Sometimes, some nodes in a custom component template are not determined by the custom component itself, but rather by the caller of the custom component. In this case, these nodes can be declared as "abstract nodes."

For example, let's implement a "selectable group" component that can contain either radio buttons (custom-radio) or checkboxes (custom-checkbox). The FXML for this component can be written as follows:

Code example:

<!-- selectable-group.fxml -->
<view wx:for="{{labels}}">
  <label>
    <selectable disabled="{{false}}"></selectable>
    {{item}}
  </label>
</view>

Here, "selectable" is not any component declared in the usingComponents field of the JSON file, but an abstract node. It needs to be declared in the componentGenerics field:

{
  "componentGenerics": {
    "selectable": true
  }
}

# Using Components with Abstract Nodes

When using the selectable-group component, you must specify which component "selectable" refers to:

<selectable-group generic:selectable="custom-radio" />

This way, when creating an instance of this selectable-group component, the "selectable" node will generate an instance of the "custom-radio" component. Similarly, if used like this:

<selectable-group generic:selectable="custom-checkbox" />

The "selectable" node will generate an instance of the "custom-checkbox" component.

Note: The custom-radio and custom-checkbox mentioned above need to be included in the usingComponents definition section of the corresponding JSON file for this FXML.

{
  "usingComponents": {
    "custom-radio": "path/to/custom/radio",
    "custom-checkbox": "path/to/custom/checkbox"
  }
}

# Default Component for Abstract Nodes

An abstract node can specify a default component, which will be instantiated if no specific component is designated. The default component can be specified in the componentGenerics field:

{
  "componentGenerics": {
    "selectable": {
      "default": "path/to/default/component"
    }
  }
}

# Notes

  • In the generic reference generic:xxx="yyy" of a node, the value yyy can only be a static value and cannot include data binding. Therefore, the abstract node feature does not apply to scenarios where the node name is dynamically determined.

# 2.9 Custom Component Extensions

To better customize the functionality of custom components, you can use the custom component extension mechanism.

# Effects After Extension

To better understand the effects after extension, let’s look at an example:

// behavior.js
module.exports = Behavior({
  definitionFilter(defFields) {
    defFields.data.from = 'behavior'
  },
})

// component.js
Component({
  data: {
    from: 'component'
  },
  behaviors: [require('behavior.js')],
  ready() {
    console.log(this.data.from) // Here, you will find that 'behavior' is output instead of 'component'
  }
})

From the example, we can see that extending a custom component essentially provides the ability to modify the definition segment of the custom component. The example above modifies the content of the data definition segment in the custom component.

# Using Extensions

The Behavior() constructor provides a new definition segment called definitionFilter to support custom component extensions. definitionFilter is a function that, when called, injects two parameters: the first parameter is the definition object of the component/behavior using this behavior, and the second parameter is the list of definitionFilter functions of the behaviors used by this behavior.

Let’s illustrate with an example:

// behavior3.js
module.exports = Behavior({
    definitionFilter(defFields, definitionFilterArr) {},
})

// behavior2.js
module.exports = Behavior({
  behaviors: [require('behavior3.js')],
  definitionFilter(defFields, definitionFilterArr) {
    // definitionFilterArr[0](defFields)
  },
})

// behavior1.js
module.exports = Behavior({
  behaviors: [require('behavior2.js')],
  definitionFilter(defFields, definitionFilterArr) {},
})

// component.js
Component({
  behaviors: [require('behavior1.js')],
})

In the code above, one custom component and three behaviors are declared, each using the definitionFilter definition segment. Following the declaration order, the following events occur:

In summary, the definitionFilter function can be understood as follows: when A uses B, A’s declaration calls B’s definitionFilter function and passes A’s definition object to B for filtering. At this point, if B also uses C and D, B can decide whether to call C and D’s definitionFilter functions to filter A’s definition object.

# Code Example

Below is a simple implementation of computed properties for custom components using extensions:

// behavior.js
module.exports = Behavior({
  lifetimes: {
    created() {
      this._originalSetData = this.setData // Original setData
      this.setData = this._setData // Wrapped setData
    }
  },
  definitionFilter(defFields) {
    const computed = defFields.computed || {}
    const computedKeys = Object.keys(computed)
    const computedCache = {}

    // Calculate computed
    const calcComputed = (scope, insertToData) => {
      const needUpdate = {}
      const data = defFields.data = defFields.data || {}

      for (let key of computedKeys) {
        const value = computed[key].call(scope) // Calculate new value
        if (computedCache[key] !== value) needUpdate[key] = computedCache[key] = value
        if (insertToData) data[key] = needUpdate[key] // Directly insert into data, needed only during initialization
      }

      return needUpdate
    }

    // Override setData method
    defFields.methods = defFields.methods || {}
    defFields.methods._setData = function (data, callback) {
      const originalSetData = this._originalSetData // Original setData
      originalSetData.call(this, data, callback) // Perform setData on data
      const needUpdate = calcComputed(this) // Calculate computed
      originalSetData.call(this, needUpdate) // Perform setData on computed
    }

    // Initialize computed
    calcComputed(defFields, true) // Calculate computed
  }
})

Using in a component:

const beh = require('./behavior.js')
Component({
  behaviors: [beh],
  data: {
    a: 0,
  },
  computed: {
    b() {
      return this.data.a + 100
    },
  },
  methods: {
    onTap() {
      this.setData({
        a: ++this.data.a,
      })
    }
  }
})

<view>data: {{a}}</view>
<view>computed: {{b}}</view>
<button bindtap="onTap">click</button>

The implementation principle is very simple. It involves a secondary encapsulation of the existing setData method. Each time setData is called, the values of the fields in computed are calculated and then set into data to achieve the effect of computed properties.

# 2.10 Obtain Update Performance Statistics

If you want to know the cost of interface updates triggered by setData, you can use the update performance statistics interface. It will return timestamps of the main update steps for each update, which can be used to roughly estimate the update performance of custom components (or pages). For example:

Component({
  attached() { // The timing of the call cannot be earlier than attached
    this.setUpdatePerformanceListener({withDataPaths: true}, (res) => {
      console.log(res)
    })
  }
})

The setUpdatePerformanceListener method accepts an options object and a callback function listener as parameters.

The options object contains the following fields:

Field Type Description
withDataPaths Boolean Whether to return information about the changed data fields

The listener returns an object res that represents an update process triggered by setData. Depending on the timing of the setData call, the update process can generally be divided into three categories:

Each successful setData call will generate an update process, triggering the listener callback once. However, it is difficult to determine which type of update process is triggered by setData. The quality of update performance does not necessarily correlate with the specific type of update; only the returned parameter values differ.

The res object contains the following fields:

Field Type Description
updateProcessId Number The ID of this update process
parentUpdateProcessId Number For sub-updates, it returns the ID of the update process it belongs to
isMergedUpdate Boolean Whether it is a merged update. If so, updateProcessId indicates the ID of the update process it is merged into
dataPaths Array Information about the data fields updated in this update. This is returned only if withDataPaths is set to true
pendingStartTimestamp Number The timestamp when this update enters the waiting queue
updateStartTimestamp Number The timestamp when the update calculation starts
updateEndTimestamp Number The timestamp when the update calculation ends

Notes:

  • setUpdatePerformanceListener only activates statistics for the current component or page. The parentUpdateProcessId might belong to another component or page's update process and may not be included in the statistical callback. If you want to know all update processes within a page, you need to call setUpdatePerformanceListener in all components.
  • There is a slight overhead for statistics. If you want to disable statistics, pass null as the second parameter listener when calling setUpdatePerformanceListener.

# 2.11 Component Placeholder

Supported in Base Library version 3.0.38 and above. Below version 3.0.38 or without configuration, the effect remains unchanged.

When using features such as On-Demand Injection, other custom components referenced by a custom component may be unavailable during the initial rendering. In this case, to prevent the rendering process from being blocked, an unavailable custom component needs a "Component Placeholder". The base library will use the placeholder component to replace the unavailable component during rendering and will replace the placeholder component back with the actual component once it becomes available.

A custom component’s placeholder component can be another custom component or a built-in component.

# Configuration

The componentPlaceholder field in the JSON configuration corresponding to a page or custom component is used to specify the placeholder component, as follows:

{
  "usingComponents": {
    "comp-a": "../comp/compA",
    "comp-b": "../comp/compB",
    "comp-c": "../comp/compC"
  },
  "componentPlaceholder": {
    "comp-a": "view",
    "comp-b": "comp-c"
  }
}

This configuration indicates:

  • The placeholder component for comp-a is the built-in component view.
  • The placeholder component for comp-b is the custom component comp-c (its path is configured in usingComponents).

Assuming the template corresponding to this configuration is as follows:

<button ontap="onTap">Show Component</button>
<comp-a wx-if="{{ visible }}">
  <comp-b prop="{{ p }}">text in slot</comp-b>
</comp-a>

When the Mini-Program starts, visible is false, so only the button will be rendered. After clicking the button, this.setData({ visible: true }) is executed. At this point, if both comp-a and comp-b are unavailable, the page will be rendered as:

<button>Show Component</button>
<view>
  <comp-c prop="{{ p }}">text in slot</comp-c>
</view>

After comp-a and comp-b are ready, the page will be replaced with:

<button>Show Component</button>
<comp-a>
  <comp-b prop="{{ p }}">text in slot</comp-b>
</comp-a>

# Notes

  1. When a component is specified as a placeholder component (e.g., comp-c in the above example), specifying a placeholder for it is ineffective. It can be understood that if a component needs to act as a placeholder for other components, it must be available from the beginning;
  2. Currently, situations where custom components are unavailable include:
    1. When using the Subpackage Asynchronization feature, referencing components from other subpackages while the corresponding subpackage has not yet been downloaded;
    2. When using the On-Demand Injection feature, the component has not yet been injected;
  3. If a component is unavailable and its placeholder component does not exist, an error will be reported and thrown during rendering;
  4. If a component does not exist but a valid placeholder component is specified for it, the placeholder component can be rendered normally, but subsequent attempts to prepare the replacement will result in an error being reported and thrown.

# Appendix: Rendering Process Involving Placeholder Components

When the base library attempts to render a component, it first recursively checks usingComponents to collect information about all components that will be used. During this process, if a referenced component is unavailable, the base library will first check whether it has a corresponding placeholder component. If not, the base library will interrupt the rendering and throw an error; if there is one, it will mark it and use the placeholder component to replace the unavailable component during subsequent rendering. Unavailable components will attempt preparation (downloading subpackages or injecting code, etc.) after the current rendering process ends. Once the preparation process is completed, the base library will attempt to render the component again (essentially executing this process) and replace the previously rendered placeholder component.

© FinClip with ❤ , Since 2017