Overview

Similar to Page, the customized components consist of four parts: axml, js, json and acss.
There are two steps to create a customized component:

  1. Declare the customized component in json. If it is dependent on other components, it is required to declare additionally the dependent customized components.

Sample code:

copy
{
  "component": true, // mandate, the value for customized component must be true
  "usingComponents": {
    "c1":"../x/index"
  }//Dependent component
}

Parameter details:

ParameterTypeRequired Description
componentBooleanYesDeclare customized component.
usingComponentsObjectNoPath of the customized component in the dependence declaration Absolute project path starts with “/”, and relative path starts with  “./” or “../” The npm path does not start with “/”.
  1. Use the Component function to register the customized component. See Component constructor

Component parameter description:

ParameterDescriptionDocument
onInitCallback on creationComponent lifecycle.
deriveDataFromPropsCallback on creation and updateComponent lifecycle.
datalocal statusSame as Page (can be modified via setData and $spliceData).
propsAttribute transferred from outsideComponent method and external attribute-props.
methodsCustomized methodComponent method and external attribute - methods.

Sample code:

copy
// /components/customer/index.js
Component({
  mixins: [], // minxin easy reuse code
  data: { x: 1 }, // internal data of component
  props: { y: 1 }, // Can add default to attribute transferred from outside
  onInit() {}, // trigger on component creation, added in version 2.0.0
  deriveDataFromProps(nextProps) {}, // trigger on component creation and before update, added in version 2.0.0
  didMount(){}, // Lifecycle function
  didUpdate(){},
  didUnmount(){},
  methods: { // customized method
    handleTap() {
  	  this.setData({ x: this.data.x + 1}); // Can use setData to change internal attribute
    }, 
  },
})

in addition, the customized component supports slot and can build flexible page structure. See component template and style .
Sample code:

copy
<!-- // /components/customer/index.axml -->
<view>
  <view>x: {{x}}</view>
  <button onTap="handleTap">plusOne</button>
  <slot>
    <view>default slot & default value</view>
  </slot>
</view>