---
title: Component
---

## Component(config: Object)

Register a custom component. An `Object` parameter is used to specify a logical interaction behavior of the component.

```js
// File /components/foo/index.js
Component({
  options: Object,
  properties: Object,
  observers: Object,
  data: Object,
  methods: Object,
  behaviors: Array,
  lifetimes: Object,
  pageLifetimes: Object,
  relations: Array,
});
```

The preceding example shows all configuration items. In a custom component, you can use the `this` keyword to access an instance object.

## Component this instance

### Properties

| Property   | Type   | Description                                                                                 |
| ---------- | ------ | ------------------------------------------------------------------------------------------- |
| is         | String | The file path to the component.                                                             |
| id         | String | The node ID.                                                                                |
| dataset    | String | The dataset of the node.                                                                    |
| data       | Object | The data of the component, **including internal data and property values**.                 |
| properties | Object | The data of the component, **including internal data and property values**, same as `data`. |

### Methods

| Method name                | Parameter                                        | Description                                                                                                                                                               |
| -------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| setData                    | Object `newData`                                 | Sets data and renders the view layer.                                                                                                                                     |
| triggerEvent               | String `name`, Object `detail`, Object `options` | The trigger event. For more information, see [Inter-component Communication and Events](#inter-component-communication-and-events).                                       |
| createSelectorQuery        |                                                  | Creates a [SelectorQuery](/en/miniapp/develop/miniapp/api/tyml/SelectorQuery/SelectorQuery) object. The selector is used to select data within this component instance.           |
| createIntersectionObserver |                                                  | Creates an [IntersectionObserver](/en/miniapp/develop/miniapp/api/tyml/IntersectionObserver/IntersectionObserver) object. The selector is used to select data within this component instance. |
| selectComponent            | String `selector`                                | Uses the selector to search for a component instance node and returns the first matched component instance object.                                                        |
| selectAllComponents        | String `selector`                                | Uses the selector to search for component instance nodes and returns an array of matched component instance objects.                                                      |
| selectOwnerComponent       |                                                  | Selects the component instance to which the current component node belongs and returns the component instance object. This instance is referenced by the component.       |
| getRelationNodes           | String `relationKey`                             | Returns all nodes that are associated with the current relationship. For more information, see [relations](#relations).                                                   |

## options

Declares the rendering behaviors and data interactions of a custom component.

| Property        | Type    | Required | Description                                                                                                                                                                |
| --------------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| pureDataPattern | regexp  | No       | Pure data fields are the `data` fields that do not participate in interface rendering. They can be used to improve the update performance of pages.                        |
| styleIsolation  | string  | No       | The style isolation configuration of the component to declare the rendering method of the current component style.                                                         |
| multipleSlots   | Boolean | No       | Enables the multi-slot feature in the component definition.                                                                                                                |
| addGlobalClass  | Boolean | No       | Adds a global style. This setting achieves a similar result to that of `styleIsolation=apply-shared`, but has a lower priority than the configuration of `styleIsolation`. |

### styleIsolation

> This property is supported in the base library 2.0.0 and later. Valid values:

- `isolated` indicates that the style isolation is enabled. Styles specified via `class` (default styles in normal cases) are not mutually affected inside or outside a custom component.
- `apply-shared` indicates that the `css` style of the page will determine the style of a custom component. However, the style specified in `css` of a custom component will not determine the style of the page.
- `shared` indicates that the `css` style of the page will determine the style of a custom component, and the styles specified in `css` of a custom component will also determine the style of the page and other custom components that have `apply-shared` or `shared` configured. This option is unavailable in plug-ins.

## properties

Declares the property settings and data processing logic of a custom component. Each key-value pair represents a property name and is written in camel case. The type of property value is defined with `type` and supports `String`, `Number`, `Boolean`, `Object`, and `Array`. The type can also be set to `null` to specify that the type is unlimited. `value` can be used to specify a default value. If not specified, it is `null`. You can use `observer()` to listen for changes in the value.

```js
Component({
  properties: {
    myName: {
      type: String,
      value: 'smart',
      observer(newValue, oldValue) {
        // do something
      },
    },
  },
});
```

Note: In the definitions of `properties`, a property name is written in camel case, for example, `myName`. When you set a property value in `tyml`, letters can be concatenated with hyphens (-) in a property name, for example, `<tag-name my-name="smart" />`.

**tips**

We recommend that you define a specific property type in most cases. This way, you can get a definite type of value when you set a property value to a literal in `tyml`. Example:

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

In this case, the property type of a custom component must be `Number`. `min` and `max` are respectively assigned `1` and `5`, rather than `"1"` and `"5"`. Example:

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

## observers

A data listener is used to listen for and respond to changes in any properties or data fields. You can define functions with property names, data names, and wildcard characters (`*`) to handle responses.

```js
Component({
  observers: {
    'value1, value2': function (value1, value2) {
      // Triggered when this.setData represents data.
    },
    'some.subfield': function (subfield) {
      // Triggered when this.data.some.subfield is set via setData
      // (Also triggered when this.data.some is set via setData)
      subfield === this.data.some.subfield;
    },
    'arr[12]': function (arr12) {
      // Triggered when this.data.arr[12] is set via setData
      // (Also triggered when this.data.arr is set via setData)
      arr12 === this.data.arr[12];
    },
    'some.field.**': function (field) {
      // Triggered when setData is used to set this.data.some.field itself or any of its sub-data fields
      // (Also triggered when this.data.some is set via setData)
      field === this.data.some.field;
    },
    '**': function () {
      // Triggered upon each setData operation
    },
  },
});
```

**Things to note**

- Data listeners are used to listen for the data fields that are set via `setData`. Even if the values of these data fields do not change, the data listeners will still be triggered.
- Note that if you use `setData` to set the monitored data fields in the data listener function, this can create an infinite loop.
- Compared to `properties.field.observer` for a property, a data listener is more powerful with better performance.

## data

The data object and `properties` of a custom component are used together to render a component template.

```js
Component({
  properties: {
    name: {
      type: String,
      value: 'smart',
    },
  },
  data: { age: 18 },
});
```

```html
<view>{{name}}: {{age}}</view>
```

## methods

Logical interaction behaviors of a custom component are combined with component instance methods to implement user operations, data changes, and event communication. You can use `this` to access the component instance in the function.

```js
Component({
  methods: {
    say() {
      this.setData({ name: 'hello world' });
    },
  },
});
```

## lifetimes

The lifecycle of a custom component, used to handle response events.

| Lifecycle | Parameter    | Description                                                            |
| --------- | ------------ | ---------------------------------------------------------------------- |
| created   | None.        | Executed when a component instance is created.                         |
| attached  | None.        | Executed when a component instance is added to the page node tree.     |
| ready     | None.        | Executed when the component layout is completed in the view layer.     |
| moved     | None.        | Executed when a component instance is relocated on the page node tree. |
| detached  | None.        | Executed when a component instance is removed from the page node tree. |
| error     | Object Error | Executed when a component method returns an error.                     |

```js
Component({
  lifetimes: {
    attached() {
      // Executed when a component instance is added to the page node tree.
    },
    ready() {
      // Executed when the component layout is completed in the view layer.
    },
    detached() {
      // Executed when a component instance is removed from the page node tree.
    },
  },
});
```

## pageLifetimes

The lifecycle declaration object for the page on which a custom component resides, used to handle response events.

| Lifecycle | Parameter | Description                                                            |       |
| --------- | --------- | ---------------------------------------------------------------------- | ----- |
| show      | None.     | Executed when the page on which a custom component resides is shown.   |       |
| hide      | None.     | Executed when the page on which a custom component resides is hidden.  |       |
| resize    | None.     | Executed when the page on which a custom component resides is resized. | 2.6.2 |

## externalClasses

The external style classes accepted by the component, please refer to [External Style Classes](/en/miniapp/develop/miniapp/framework/custom-component/tyml-tyss) for more information.

## relations

The relationship between components, used to define and use an inter-component relationship.

```js
// path/to/custom-ul.js
Component({
  relations: {
    './custom-li': {
      type: 'child', // The linked target node must be a child node.
      linked(target) {
        // Executed each time custom-li is inserted. "target" is the instance object of this node and triggered after the attached lifecycle of this node.
      },
      linkChanged(target) {
        // Executed each time custom-li is moved. "target" is the instance object of this node and triggered after the moved lifecycle of this node.
      },
      unlinked(target) {
        // Executed each time custom-li is removed. "target" is the instance object of this node and triggered after the detached lifecycle of this node.
      },
    },
  },
});
```

```js
// path/to/custom-li.js
Component({
  relations: {
    './custom-ul': {
      type: 'parent', // The linked target node must be a parent node.
      linked(target) {
        // Executed after each insertion to custom-ul. "target" is the instance object of the custom-ul node and triggered after the attached lifecycle of the custom-ul node.
      },
      linkChanged(target) {
        // Executed after each move. "target" is the instance object of the custom-ul node and triggered after the moved lifecycle of the custom-ul node.
      },
      unlinked(target) {
        // Executed after each removal. "target" is the instance object of the custom-ul node and triggered after the detached lifecycle of the custom-ul node.
      },
    },
  },
});
// Note: The relations definition must be added to the definitions of both components. Otherwise, it will be invalid.
```

### Definition field of relations

The `relations` definition field includes the target component path and its corresponding options. The following table lists the available options.

| Option      | Type     | Required | Description                                                                                                                                                             |
| ----------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type        | String   | Yes      | The relative relationship of the target component, including `parent`, `child`, `ancestor`, and `descendant`.                                                           |
| linked      | Function | No       | A relationship lifecycle function. This function is triggered when the relationship is created in the page node tree after the `attached` lifecycle of the component.   |
| linkChanged | Function | No       | A relationship lifecycle function. This function is triggered when the relationship changes in the page node tree after the `moved` lifecycle of the component.         |
| unlinked    | Function | No       | A relationship lifecycle function. This function is triggered when the relationship is removed from the page node tree after the `detached` lifecycle of the component. |
| target      | String   | No       | This field defines the `behavior` of an associated target node. Component nodes that have this `behavior` configured are all associated with each other.                |

## behaviors

The 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 a `behavior`, the properties, data, and methods of the `behavior` will be merged into the component. The lifecycle functions will be called at an appropriate time point. Each component can reference multiple `behaviors`, and a `behavior` can also reference another `behavior`.

> For more information about `behaviors`, see [Behavior](/en/miniapp/develop/miniapp/framework/api/behavior).

### Usage in a component

For reference by components, behaviors can be listed one by one in the `behaviors` definition field.

```js
// my-behavior.js
export default Behavior({
  behaviors: [
    /* Reference another behavior */
  ],
  properties: { myBehaviorProperty: { type: String } },
  data: { myBehaviorData: {} },
  lifetimes: { attached() {} },
  methods: { myBehaviorMethod() {} },
});
```

```js
import myBehavior  from '/my-behavior';

Component({
  behaviors: [myBehavior],
});
```

### Overwriting and combination rules for fields with the same name

A component and the behavior that is referenced by the component can contain fields with the same name. These fields are handled based on the following rules:

- For properties or methods with the same name:

1. If the component itself has this property or method, the component's property or method will overwrite the property or method with the same name in behavior.
2. If the component itself does not have this property or method, the behavior property or method last defined in the `behaviors` field of the component will overwrite the earlier property or method with the same name.
3. Based on the previous rule, if there is a nested reference to behavior, the rule is that the parent behavior overwrites the property or method with the same name in the child behavior.

- For data fields (`data`) with the same name:

  - If data fields with the same name are all object types, the objects will be merged.
  - In other cases, a former field overwrites data in a latter field when they are sorted in the following descending order of priority: component > parent behavior > child behavior, later behavior > earlier behavior. The fields with higher priority overwrites the data in the fields with lower priority. The behavior that is last defined has the highest priority among all behavior definitions.

- Lifecycle functions do not overwrite each other, but are called one by one at the specified trigger timing:
  - For different types of lifecycle functions, follow the execution sequence of component lifecycle functions.
  - For the same type of lifecycle functions, follow these rules to execute these functions:
    - A behavior takes precedence over a component.
    - A child behavior takes precedence over the parent behavior.
    - The behavior that appears earlier takes precedence over those that appear later.
  - If the same behavior is referenced multiple times by a component, the lifecycle functions defined by the behavior will be executed only once.

## definitionFilter

The filter of definition fields, used to extend custom components.

```js
// behavior.js
export default Behavior({
  definitionFilter(defFields) {
    defFields.data.from = 'behavior';
  },
});

// component.js
import myBehavior from './behavior.js'
Component({
  data: {
    from: 'component',
  },
  behaviors: [myBehavior],
  ready() {
    console.log(this.data.from); // You can see that the output here is behavior, instead of component.
  },
});
```

In this example, extensions to the custom component enable you to modify the data definition field in the custom component. In the above example, the data definition field in the custom component is modified.

## Advanced syntax

### Inter-component communication and events

The following methods are used for communication between components.

- TYML data binding: used to set data from the parent component to the specified property of the child component. Only JSON compatible data can be set.
- Events: used for child components to transfer any type of data to a parent component.
- If the above two methods cannot meet your needs, the parent component can also get the instance object of the child component by using the `this.selectComponent` method. This allows you to directly access any data and methods of the components.

#### Listen for events

The event system is one primary method of communication between components. A custom component can trigger any events, and pages that reference the specified component can listen for these events. For more information about event concepts and usage, see [Events](/en/miniapp/develop/miniapp/framework/event/interaction).

You can listen for custom component events in the same way as with basic component events.

**Example:**

```xml
<!-- The "onMyEvent" method is called when the custom component triggers "myevent" -->
<component-tag-name bind:myevent="onMyEvent" />
```

```js
Page({
  onMyEvent(event) {
    event.detail; // The detail object provided when the custom component triggers an event.
  },
});
```

#### Trigger an event

When a custom component triggers an event, use the `triggerEvent` method to specify the event name, detail object, and event options.

**Example:**

```xml
<!-- In the custom component -->
<button bind:tap="onTap">Tap this button to trigger the "myevent" event</button>
```

```js
Component({
  properties: {},
  methods: {
    onTap() {
      var myEventDetail = {}; // The detail object, provided to the event listener function.
      this.triggerEvent('myevent', myEventDetail);
    },
  },
});
```

### Component template slot

A slot node can be provided in the component tyml to host the tyml structure that is provided by the component user.

The component tyml supports one slot or multiple slots. `multipleSlots: true` must be enabled.

To use multiple slots in the component tyml, you can distinguish them by different names.

```html
<! -- Component template -->
<view class="wrapper">
  <slot name="before"></slot>
  <view>Internal details of the component</view>
  <slot name="after"></slot>
</view>
```

You can use the slot property to insert nodes into different slots.

```html
<! -- Page template where the component is referenced -->
<view>
  <component-tag-name>
    <! -- This part is added to the <slot name="before">
    location of the component -->
    <view slot="before"
      >This is inserted in the slot name="before" of the component</view
    >
    <! -- This part is added to the <slot name="after">
    location of the component -->
    <view slot="after"
      >This is inserted in the slot name="after" of the component</view
    >
  </component-tag-name>
</view>
```

### Pure data fields in component data

In some cases, some fields in `data` including fields set by `setData` are neither displayed on the interface nor passed to other components, but are only used inside the current component.

These data fields are known as pure data fields. They are only recorded in `this.data`, but not used in any UI rendering process. This helps to improve the update performance of pages.

To specify a pure data field, you can specify `pureDataPattern` as a regular expression in the `options` definition field of the `Component` constructor. Fields whose names conform to this regular expression are pure data fields.

**Example:**

```js
Component({
  options: {
    pureDataPattern: /^_/, // Specify all data fields starting with an underscore (_) as pure data fields.
  },
  data: {
    a: true, // General data field
    _b: true, // Pure data field
  },
  methods: {
    myMethod() {
      this.data._b; // Pure data fields can be obtained in this.data.
      this.setData({
        c: true, // General data field
        _d: true, // Pure data field
      });
    },
  },
});
```

The pure data fields in the above components will not be applied to TYML:

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

#### Pure data fields in the component property

A property that conforms to `pureDataPattern` regular expression can also be specified as a pure data field.

Just like a general property, a pure data field in the property can receive an external property value. However, the property value cannot be used directly in TYML of the component.

**Example:**

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

Note: The `observer` property in the pure data fields will never be triggered. You can use a [data listener](/en/miniapp/develop/miniapp/framework/custom-component/observers) to listen for the changes in the property value.

#### Use a data listener to listen for pure data fields

A [data listener](/en/miniapp/develop/miniapp/framework/custom-component/observers) is used to listen for the pure data fields, just like listening for a general data field. In this way, you can implement interface changes by listening for and responding to changes in pure data fields.

The following example shows how to convert a `JavaScript` timestamp to a custom component with readable time.

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

```xml
<view>{{timeString}}</view>
```
