Create custom component

更新时间:
复制 MD 格式

A custom component is a reusable UI unit composed of axml, js, json, and acss files that you can declare and register for use across pages.

Like a Page, a custom component consists of axml, js, json, and acss files. To create a custom component:

  1. Declare a component.
  2. Use the Component function to register the custom component.

The following example shows a basic component:

// app.json
{
  "component": true
}
// /components/customer/index.js
Component({
  mixins: [], // minxin facilitates code reuse.
  data: { x: 1 }, // Internal component data.
  props: { y: 1 }, // Adds default values for the properties passed from the external.
  didMount(){}, // Life cycle function.
  didUpdate(){},
  didUnmount(){},
  methods: { // Custom method.
    handleTap() {
        this.setData({ x: this.data.x + 1}); // setData can be used to change the internal property.
    },
  },
})
<!-- /components/customer/index.axml -->
<view>
  <view>x: {{x}}</view>
  <button onTap="handleTap">plusOne</button>
  <slot>
    <view>default slot & default value</view>
  </slot>
</view>