# Component Constructor
The Component
constructor is used to define components. You can specify component properties, data, and methods when calling the Component
constructor.
For specific definitions and usage of the parameters, see the Component reference documentation.
Component({
behaviors: [],
properties: {
myProperty: { // Property name
type: String,
value: ''
},
myProperty2: String // Simplified definition
},
data: {}, // Private data, used for template rendering
lifetimes: {
// Lifecycle function, which can be a function or a method name defined in the methods field
attached: function () { },
moved: function () { },
detached: function () { },
},
// Lifecycle function, which can be a function or a method name defined in the methods field
attached: function () { }, // The declaration in the attached field is overwritten by that in the lifetimes field
ready: function() { },
pageLifetimes: {
// Component page lifecycle function
show: function () { },
hide: function () { },
resize: function () { },
},
methods: {
onMyButtonTap: function(){
this.setData({
// The properties and data are updated in the same way as with the page data
})
},
// The internal method starts with an underscore
_myPrivateMethod: function(){
// Here, data.A[0].B is set to 'myPrivateData'
this.setData({
'A[0].B': 'myPrivateData'
})
},
_propertyChange: function(newVal, oldVal) {
}
}
})
# Construct a Page via Component Constructor
In fact, the Mini Program's page can also be considered as a custom component. Thus, its page can also be constructed using the Component
constructor, as it has the same definition field and instance method as a general component. However, you must include the usingComponents
definition field in the corresponding json file.
In this case, the properties of the component can be used to receive page parameters, such as visited pages /pages/index/index?paramA=123¶mB=xyz
. If the property paramA
or paramB
is declared, they will be assigned 123
or xyz
.
The page's lifecycle method (i.e., the method starting with on
) must be written in the methods
definition field.
Code example:
{
"usingComponents": {}
}
Component({
properties: {
paramA: Number,
paramB: String,
},
methods: {
onLoad: function() {
this.data.paramA // Value of page parameter paramA
this.data.paramB // Value of page parameter paramB
}
}
})