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

数据监听器可以用于监听和响应任何属性和数据字段的变化。从小程序基础库版本 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>
相关推荐
游戏开发爱好者85 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_915106326 小时前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106327 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息8 小时前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
光影少年1 天前
AIGC + Taro / 小程序
小程序·aigc·taro
2501_915918411 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
2501_916007471 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
天空属于哈夫克31 天前
Go 语言实战:构建一个企微外部群“技术贴收藏夹”小程序后端
小程序·golang·企业微信
菜鸟una1 天前
【微信小程序+Taro 3+NutUI 3】input (nut-input) 、 textarea (nut-texteare)类型使用避坑
前端·vue.js·微信小程序·小程序·taro
计算机毕设指导61 天前
基于微信小程序的校园二手交易系统【源码文末联系】
java·spring boot·spring·微信小程序·小程序·tomcat·maven