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

数据监听器可以用于监听和响应任何属性和数据字段的变化。从小程序基础库版本 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>
相关推荐
2501_916007473 分钟前
iOS 混淆与团队协作,研发、安全、运维、测试如何在加固流程中高效配合(iOS 混淆、ipa 加固、协作治理)
android·ios·小程序·https·uni-app·iphone·webview
2501_916008896 小时前
iOS 不上架怎么安装?多种应用分发方式解析,ipa 文件安装、企业签名、Ad Hoc 与 TestFlight 实战经验
android·macos·ios·小程序·uni-app·cocoa·iphone
CRMEB定制开发9 小时前
PHP多商户接入阿里云识图找商品
android·阿里云·小程序·php·商城系统·微信商城·crmeb
00后程序员张9 小时前
iOS App 混淆实战,在源码不可用情况下的成品加固与测试流程
android·ios·小程序·https·uni-app·iphone·webview
说私域11 小时前
基于开源AI智能名片与链动2+1模式的S2B2C商城小程序研究:构建“信息找人”式精准零售新范式
人工智能·小程序·开源
知识分享小能手11 小时前
微信小程序入门学习教程,从入门到精通,微信小程序页面交互 —— 知识点详解与案例实现(3)
前端·javascript·学习·react.js·微信小程序·小程序·交互
说私域12 小时前
开源AI智能名片链动2+1模式S2B2C商城小程序在公益课裂变法中的应用与影响研究
人工智能·小程序
Tartly12 小时前
掌中智汇,运筹帷幄 - 全新ASUS华硕智汇商擎小程序上线
小程序
私人珍藏库12 小时前
[吾爱大神原创] wx小程序自动解包工具界面版1.0.0
小程序
2501_9160137413 小时前
iOS 26 设备文件管理实战指南,文件访问、沙盒导出、系统变更与 uni-app 项目适配
android·ios·小程序·uni-app·cocoa·iphone·webview