更新時(shí)間:2023年11月06日15時(shí)31分 來源:傳智教育 瀏覽次數(shù):
1. data 數(shù)據(jù)
在小程序組件中,用于組件模板渲染的私有數(shù)據(jù),需要定義到 data 節(jié)點(diǎn)中,示例如下:
Component({
/**
*組件的初始數(shù)據(jù)
*/
data: {
count: O
}
})
2. methods 方法
在小程序組件中,事件處理函數(shù)和自定義方法需要定義到 methods 節(jié)點(diǎn)中,示例代碼如下:
Component({
methods:{ //組件的方法列表【包含事件處理函數(shù)和自定義方法】
addCount(){//事件處理函數(shù)
this.setData({ count: this.data.count + 1 })
this._showCount()// 通過 this 直接調(diào)用自定義方法
},
_showCount(){ //自定義方法建議以_開頭
wx.showToast({
title:'count值為:'+this.data.count,
icon: 'none'
})
}
}
})
3. properties 屬性在小程序組件中,properties 是組件的對外屬性,用來接收外界傳遞到組件中的數(shù)據(jù),示例代碼如下:
Component({
//屬性定義
properties: {
max:{ //完整定義屬性的方式【當(dāng)需要指定屬性默認(rèn)值時(shí),建議使用此方式】
type:Nknber,//屬性值的數(shù)據(jù)類型
value: 10 //屬性默認(rèn)值
},
max: Number //簡化定義屬性的方式【不需指定屬性默認(rèn)值時(shí),可以使用簡化方式】
}
})
<my-test1 max="10"></my-test1>
4. data 和 properties 的區(qū)別
在小程序的組件中,properties 屬性和 data 數(shù)據(jù)的用法相同,它們都是可讀可寫的,只不過:
data 更傾向于存儲(chǔ)組件的私有數(shù)據(jù)。
properties 更傾向于存儲(chǔ)外界傳遞到組件中的數(shù)據(jù)。
Component({
methods: {
showInfo(){
consale.log(this.data) //輸出結(jié)果:{count:0,max:10}
console.log(this.properties) //輸出結(jié)果:{count:0,max:10}
//結(jié)果為 true,證明 data數(shù)據(jù)和properties屬性【在本質(zhì)上是一樣的、都是可讀可寫的】
console.log(this.data === this.properties)
}
}
})
5. 使用 setData 修改 properties 的值
由于 data 數(shù)據(jù)和 properties 屬性在本質(zhì)上沒有任何區(qū)別,因此 properties 屬性的值也可以用于頁面渲染,或使用 setData 為 properties 中的屬性重新賦值,示例代碼如下:
//在組件的.wxml 文件中使用properties 屬性的值
<view>max屬性的值為:{{max}}</view>
Component({
properties:{max:Number },//定義屬性
methods:{
addCount() {
this.setData({max:this.properzies.max+1 })//使用 setData修改屬性的值
}
}
})