微信小程序数据监听器小案例

一 组件 .js

Component({

  /**

   * 组件的初始数据

   */

  data: {

    _rgb: { // rgb 的颜色值对象

      r: 0,

      g: 0,

      b: 0

    },

    fullColor: '0, 0, 0' // 根据 rgb 对象的三个属性,动态计算 fullColor 的值

  },

  /**

   * 组件的方法列表

   */

  methods: {

    changeR() { // 修改 rgb 对象上 r 属性的值

      this.setData({

        '_rgb.r': this.data._rgb.r + 5 > 255 ? 255 : this.data._rgb.r + 5

      })

    },

    changeG() { // 修改 rgb 对象上 g 属性的值

      this.setData({

        '_rgb.g': this.data._rgb.g + 5 > 255 ? 255 : this.data._rgb.g + 5

      })

    },

    changeB() { // 修改 rgb 对象上 b 属性的值

      this.setData({

        '_rgb.b': this.data._rgb.b + 5 > 255 ? 255 : this.data._rgb.b + 5

      })

    },

    _randomColor() {

      this.setData({

        _rgb: {

          r: Math.floor(Math.random() * 256),

          g: Math.floor(Math.random() * 256),

          b: Math.floor(Math.random() * 256)

        }

      })

    }

  },

  // 监听对象中指定属性的变化

  observers: {

    '_rgb.**': function (obj) { // 监听 rgb 对象上 r、g、b 三个子属性的变化 如果某个对象中需要被监听的属性太多,为了方便,可以使用通配符 ** 来监听对象中所有属性的变化

      this.setData({ // 为 data 中的 fullColor 重新赋值

        fullColor: `${obj.r}, ${obj.g}, ${obj.b}`

      })

    }

  }

})

二 .wxml 结构

<view style="background-color: rgb({{fullColor}});" class="colorBox">颜色值:{{fullColor}}</view>

<button size="mini" type="default" bindtap="changeR">R</button>

<button size="mini" type="primary" bindtap="changeG">G</button>

<button size="mini" type="warn" bindtap="changeB">B</button>

三 .wxss 样式

.colorBox {

  line-height: 200rpx;

  font-size: 24rpx;

  color: white;

  text-shadow: 0rpx 0rpx 2rpx black;

  text-align: center;

}

四 测试效果

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值