# Component constructor
Componentconstructors can be used to define components. Calling theComponentbuilder can specify components' properties, data, methods, and so on.
Please refer to the Component reference document for detailed parameter meaning and usage.
Component({
behaviors: [],
properties: {
myProperty: { // 属性名
type: String,
value: ''
},
myProperty2: String // 简化的定义方式
},
data: {}, // 私有数据,可用于模板渲染
lifetimes: {
// 生命周期函数,可以为函数,或一个在methods段中定义的方法名
attached: function () { },
moved: function () { },
detached: function () { },
},
// 生命周期函数,可以为函数,或一个在methods段中定义的方法名
attached: function () { }, // 此处attached的声明会被lifetimes字段中的声明覆盖
ready: function() { },
pageLifetimes: {
// 组件所在页面的生命周期函数
show: function () { },
hide: function () { },
resize: function () { },
},
methods: {
onMyButtonTap: function(){
this.setData({
// 更新属性和数据的方法与更新页面数据的方法类似
})
},
// 内部方法建议以下划线开头
_myPrivateMethod: function(){
// 这里将 data.A[0].B 设为 'myPrivateData'
this.setData({
'A[0].B': 'myPrivateData'
})
},
_propertyChange: function(newVal, oldVal) {
}
}
})
# Constructing a page with the Component constructor
In fact, Weixin Mini Program pages can also be considered custom components.Thus, a page can also be constructed with theComponentconstructor and have the same definition segments and instance methods as a normal component.However, this requires that the corresponding json file contains ausingComponentsdefinition section.
At this point, the properties of the component can be used to receive parameters of the page, such as accessing the page/ pages / index / index?ParamA = 123 ¶ mB = xyz, if the declaration has the attributeparamAorparamB, then they are assigned either123orxyz。
The page lifecycle methods (i.e. methods beginning withon) should be written in themethodsdefinition paragraph.
Code example:
{
"usingComponents": {}
}
Component({
properties: {
paramA: Number,
paramB: String,
},
methods: {
onLoad: function() {
this.data.paramA // 页面参数 paramA 的值
this.data.paramB // 页面参数 paramB 的值
}
}
})
One of the advantages of usingComponentconstructors to construct pages is thatbehaviorscan be used to extract common sections of code from all pages.
For example, executing the same code when all pages are created and destroyed can be extracted intobehaviors.
Code example:
// page-common-behavior.js
module.exports = Behavior({
attached: function() {
// 页面创建时执行
console.info('Page loaded!')
},
detached: function() {
// 页面销毁时执行
console.info('Page unloaded!')
}
})
// Page A
var pageCommonBehavior = require('./page-common-behavior')
Component({
behaviors: [pageCommonBehavior],
data: { /* ... */ },
methods: { /* ... */ },
})
// Page B
var pageCommonBehavior = require('./page-common-behavior')
Component({
behaviors: [pageCommonBehavior],
data: { /* ... */ },
methods: { /* ... */ },
})