新聞中心
Component 構(gòu)造器
Component 構(gòu)造器可用于定義組件,調(diào)用 Component 構(gòu)造器時可以指定組件的屬性、數(shù)據(jù)、方法等。

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、成都微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了松嶺免費建站歡迎大家使用!
詳細(xì)的參數(shù)含義和使用請參考 Component 參考文檔。
Component({
behaviors: [],
properties: {
myProperty: { // 屬性名
type: String,
value: ''
},
myProperty2: String // 簡化的定義方式
},
data: {}, // 私有數(shù)據(jù),可用于模板渲染
lifetimes: {
// 生命周期函數(shù),可以為函數(shù),或一個在methods段中定義的方法名
attached: function () { },
moved: function () { },
detached: function () { },
},
// 生命周期函數(shù),可以為函數(shù),或一個在methods段中定義的方法名
attached: function () { }, // 此處attached的聲明會被lifetimes字段中的聲明覆蓋
ready: function() { },
pageLifetimes: {
// 組件所在頁面的生命周期函數(shù)
show: function () { },
hide: function () { },
resize: function () { },
},
methods: {
onMyButtonTap: function(){
this.setData({
// 更新屬性和數(shù)據(jù)的方法與更新頁面數(shù)據(jù)的方法類似
})
},
// 內(nèi)部方法建議以下劃線開頭
_myPrivateMethod: function(){
// 這里將 data.A[0].B 設(shè)為 'myPrivateData'
this.setData({
'A[0].B': 'myPrivateData'
})
},
_propertyChange: function(newVal, oldVal) {
}
}
})
使用 Component 構(gòu)造器構(gòu)造頁面
事實上,小程序的頁面也可以視為自定義組件。因而,頁面也可以使用 Component 構(gòu)造器構(gòu)造,擁有與普通組件一樣的定義段與實例方法。但此時要求對應(yīng) json 文件中包含 usingComponents 定義段。
此時,組件的屬性可以用于接收頁面的參數(shù),如訪問頁面 /pages/index/index?paramA=123¶mB=xyz ,如果聲明有屬性 paramA 或 paramB ,則它們會被賦值為 123 或 xyz 。
頁面的生命周期方法(即 on 開頭的方法),應(yīng)寫在 methods 定義段中。
代碼示例:
{
"usingComponents": {}
}
Component({
properties: {
paramA: Number,
paramB: String,
},
methods: {
onLoad: function() {
this.data.paramA // 頁面參數(shù) paramA 的值
this.data.paramB // 頁面參數(shù) paramB 的值
}
}
})
使用 Component 構(gòu)造器來構(gòu)造頁面的一個好處是可以使用 behaviors 來提取所有頁面中公用的代碼段。
例如,在所有頁面被創(chuàng)建和銷毀時都要執(zhí)行同一段代碼,就可以把這段代碼提取到 behaviors 中。
代碼示例:
// page-common-behavior.js
module.exports = Behavior({
attached: function() {
// 頁面創(chuàng)建時執(zhí)行
console.info('Page loaded!')
},
detached: function() {
// 頁面銷毀時執(zhí)行
console.info('Page unloaded!')
}
})
// 頁面 A
var pageCommonBehavior = require('./page-common-behavior')
Component({
behaviors: [pageCommonBehavior],
data: { /* ... */ },
methods: { /* ... */ },
})
// 頁面 B
var pageCommonBehavior = require('./page-common-behavior')
Component({
behaviors: [pageCommonBehavior],
data: { /* ... */ },
methods: { /* ... */ },
})
分享題目:創(chuàng)新互聯(lián)小程序教程:微信小程序Component構(gòu)造器
文章起源:http://www.dlmjj.cn/article/ccsocsj.html


咨詢
建站咨詢
