Similar to a page, a custom component also consists of JSON, HXML, CSS, and JS files.
The directory structure of the index page and my-component component is as follows:
// Structure of the index page and custom my-component. └── index ├── components │ └── my-component │ ├── my-component.css │ ├── my-component.js │ ├── my-component.json │ └── my-component.hxml ├── index.css ├── index.js ├── index.json └── index.hxml
To define a custom component, perform the following steps:
Declare "component": true in the JSON file.
{ "component": true} Call the construction method of Component in the JS file.
// my-component.js
Component({
// Define the internal data of the component.
data: {
name: 'custom-component'
},
// Customize the internal methods of the component.
methods: {
customMethod() {}
}
}) Compile the component template in the HXML file. For details, see "Component Template".
<view>{{name}}</view> Compile the component style in the CSS file. For details, see "Component Style and Isolation Strategy".
/* my-component.css */
/* Internal style of the component */
.name {
background: #fff;
}