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

数据监听器可以用于监听和响应任何属性和数据字段的变化。从小程序基础库版本 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>
相关推荐
m0_5873830013 小时前
深度解析24小时自助健身房系统开发:从架构设计到落地部署
人工智能·小程序·数据挖掘·系统架构·需求分析
镭封1 天前
基于微信小程序的移动端AI配音工作流设计
人工智能·小程序·媒体
FX1317887KP_1 天前
PET口语备考攻略:发音、语法、表达,三个问题怎么同时解决
小程序·ket口语·pet口语·fce备考·剑桥英语
地球@+jdhb441 天前
企业私域运营新趋势:快手短视频平台跳转小程序企微卡片链路搭建成为商家运营重点
小程序·企业微信
程序鉴定师1 天前
2026年深圳小程序/App开发公司技术选型指南:从架构设计到交付标准全维度评估
java·小程序·uni-app·php·objective-c
Q26433650231 天前
【有源码】基于uni-app的旅游行程规划小程序-基于微信小程序的智慧文旅综合服务平台
java·微信小程序·小程序·uni-app·毕业设计·springboot·源代码
网硕互联的小客服1 天前
微信小程序多种跳转页面方式教学
微信小程序·小程序·notepad++
m0_587383002 天前
24小时自助健身房软硬件解决方案实战指南:从架构设计到部署实施
java·spring·小程序·架构·需求分析
m0_587383002 天前
24小时自助健身房软硬件解决方案实战:从架构设计到部署指南
java·spring·小程序·架构·需求分析
CRMEB系统商城2 天前
前后端技术栈全面换代!CRMEB 多商户(Java)v3.0更新预告
java·开发语言·小程序·php