一 什么是數(shù)據(jù)監(jiān)聽器
數(shù)據(jù)監(jiān)聽器用于監(jiān)聽和響應(yīng)任何屬性和數(shù)據(jù)字段的變化,從而執(zhí)行特定的操作。它的作用類似于 vue 中的?watch 偵聽器。在小程序組件中,數(shù)據(jù)監(jiān)聽器的基本語法格式如下。
Component({
??observers: {
????'字段A,?字段B': function (字段A的新值,?字段B的新值) {
? ? ? // do something
????}
??}文章來源:http://www.zghlxwxcb.cn/news/detail-485923.html
})文章來源地址http://www.zghlxwxcb.cn/news/detail-485923.html
二 數(shù)據(jù)監(jiān)聽器的基本用法
1 組件的 UI 結(jié)構(gòu)如下
<view>{{n1}} + {{n2}} = {{sum}}</view>
<button bindtap="addN1">n1+1</button>
<button bindtap="addN2">n2+1</button>
2?組件的 .js?文件代碼如下
Component({
??/**
???* 組件的初始數(shù)據(jù)
???*/
??data: {
????n1: 0,
????n2: 0,
????sum: 0
??},
??/**
???* 組件的方法列表
???*/
??methods: {
????addN1() {
??????this.setData({
????????n1: this.data.n1 + 1
??????})
????},
????addN2() {
??????this.setData({
????????n2: this.data.n2 + 1
??????})
????}
??},
??observers: { //?數(shù)據(jù)監(jiān)聽數(shù)據(jù)
????'n1, n2': function (newN1, newN2) { //?監(jiān)聽?n1?和 n2?的數(shù)據(jù)變化
??????this.setData({
????????sum: newN1 + newN2 //?通過監(jiān)聽器,自動(dòng)計(jì)算?sum?的值
??????})
????}
??}
})
三 監(jiān)聽對象屬性的變化
數(shù)據(jù)監(jiān)聽器支持監(jiān)聽對象中單個(gè)或多個(gè)屬性的變化,示例語法如下。
Component({
??observers: {
????'對象.屬性A,?對象.屬性B': function (屬性A的新值,?屬性B的新值) {
? ? ? //?觸發(fā)此監(jiān)聽器的 3?種情況
? ? ? // 【為屬性A賦值】?使用?setDate?設(shè)置? this.data.對象.屬性A?時(shí)觸發(fā)
? ? ? // 【為屬性B賦值】 使用 setDate 設(shè)置??this.data.對象.屬性B 時(shí)觸發(fā)
??????// 【直接為對象賦值】 使用 setDate 設(shè)置??this.data.對象 時(shí)觸發(fā)
? ? ? // do something...
????}
??}
})
到了這里,關(guān)于微信小程序的數(shù)據(jù)監(jiān)聽器的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!