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

数据监听器可以用于监听和响应任何属性和数据字段的变化。从小程序基础库版本 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>
相关推荐
少云清5 小时前
【功能测试】5_小程序项目 _抓包修改轮播图(重要)
小程序
從南走到北6 小时前
JAVA代驾小程序源码代驾跑腿APP源码
java·开发语言·微信·微信小程序·小程序
小小王app小程序开发6 小时前
招工招聘小程序运营风险清单:资质备案 + 信息审核 + 服务履约避坑实操
小程序
2501_915921438 小时前
混合开发应用安全方案,在多技术栈融合下构建可持续、可回滚的保护体系
android·安全·ios·小程序·uni-app·iphone·webview
q_19132846958 小时前
基于SpringBoot2+Vue2+uniapp的考研社区论坛网站及小程序
java·vue.js·spring boot·后端·小程序·uni-app·毕业设计
pearbing8 小时前
多平台发力:小程序搜索优化的实用策略指南
小程序·小程序搜索排名·小程序优化·小程序搜索排名优化·小程序搜索优化·小程序seo
2501_915106329 小时前
Charles抓包怎么用 Charles抓包工具详细教程、网络调试方法、HTTPS配置与手机抓包实战
网络·ios·智能手机·小程序·https·uni-app·webview
00后程序员张9 小时前
Fastlane 结合 开心上架,构建跨平台可发布的 iOS 自动化流水线实践
android·运维·ios·小程序·uni-app·自动化·iphone
游戏开发爱好者810 小时前
iOS 性能测试的工程化方法,构建从底层诊断到真机监控的多工具测试体系
android·ios·小程序·https·uni-app·iphone·webview
2501_9160088910 小时前
iOS App 混淆的真实世界指南,从构建到成品 IPA 的安全链路重塑
android·安全·ios·小程序·uni-app·cocoa·iphone