小程序组件内的数据监听器

数据监听器可以用于监听和响应任何属性和数据字段的变化。从小程序基础库版本 2.6.1 开始支持。

有时,在一些数据字段被 setData 设置时,需要执行一些操作。例如, 一个值取决于另外两个值的变化,this.data.sum 永远是 this.data.numberA 与 this.data.numberB 的和。此时,可以使用数据监听器进行如下实现。

创建组件cpn-observers

xml 复制代码
<view class="container">
  <view>numberA: {{numberA}}</view>
  <view>numberB: {{numberB}}</view>
  <view class="btn-flex">
    <button class="btn" data-number="A" bind:tap="increment">numberA+</button>
    <button class="btn" data-number="A" bind:tap="decrement">numberA-</button>
    <button class="btn" data-number="B" bind:tap="increment">numberB+</button>
    <button class="btn" data-number="B" bind:tap="decrement">numberB-</button>
  </view>
</view>
<view>子组件中根据父组件传递的值求和:{{numberA}} + {{numberB}} = {{sum}}</view>
javascript 复制代码
Component({
  /**
   * 组件的初始数据
   */
  data: {
    numberA: 0,
    numberB: 1,
  },
  lifetimes: {
    attached(){
      this.setData({
        sum: this.properties.numberA + this.properties.numberB
      })
    }
  },
  observers: {
    'numberA, numberB': function(numberA, numberB) {
      // 在 numberA 或者 numberB 被设置时,执行这个函数
      this.setData({
        sum: numberA + numberB
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    increment(e){
      const {number} = e.currentTarget.dataset
      if (number === 'A') {
        this.setData({
          numberA: this.data.numberA + 1
        })
      }else if (number === 'B') {
        this.setData({
          numberB: this.data.numberB + 1
        })
      }
    },
    decrement(e){
      const {number} = e.currentTarget.dataset
      if (number === 'A') {
        this.setData({
          numberA: this.data.numberA - 1
        })
      }else if (number === 'B') {
        this.setData({
          numberB: this.data.numberB - 1
        })
      }
    },
  }
})
css 复制代码
.btn-flex{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-evenly;
}
.btn{
  width: 40% !important;
  margin: 10rpx;
}

页面中引用组件

javascript 复制代码
{
  "usingComponents": {
    "cpn-observers": "./cpn-observers"  //具体路径根据实际位置更改
  }
}
xml 复制代码
<view class="container">
  <cpn-observers />
</view>
相关推荐
李纲明15 小时前
微信小程序 getSystemInfo 提示已废弃、屏幕高度算错胶囊还对不齐?getWindowInfo 和 getDeviceInfo 怎么接才稳
javascript·微信小程序·小程序·小程序开发·devdiy
dreams_dream17 小时前
微信小程序-使用npm包
微信小程序·小程序·npm
caoliaoerweima20 小时前
草料二维码小程序上线活码编辑器:手机上也能编辑活码了
智能手机·小程序·编辑器·草料二维码
dreams_dream3 天前
微信小程序:页面事件-上拉触底
微信小程序·小程序
wafrdggh4 天前
2026电商快递批量查询怎么用?固乔助手模板设置评测
大数据·数据库·小程序
wafrdggh5 天前
2026 商城小程序平台哪个价格合理?把跨境附加成本这个坑算透
大数据·小程序
恩创软件开发7 天前
自助KTV系统管理员续单功能
经验分享·小程序
AI源码9 天前
在线考试小程序
小程序·notepad++
2501_916008899 天前
iPhone 设备信息查看,用 KeyMob 看型号、序列号、电池健康和 UDID
android·ios·小程序·https·uni-app·iphone·webview
云-缩影10 天前
做微信小程序,自建服务器还是用云托管:技术选型对比
服务器·微信小程序·小程序