微信小程序-自定义组件之数据监听器

在这里插入图片描述
点击R G B改变view颜色

<!--components/test/test.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>
<!-- <view>{{rgb.r}},{{rgb.g}},{{rgb.b}}</view> -->
// components/test/test.js
Component({
  options:{
    //指定_开头的为纯数据字段
    pureDataPattern:/^_/
  },
  properties: {

  },
  data: {
    _rgb:{
      r:0,
      g:0,
      b:0
    },
    fullColor:'0, 0, 0'
  },
  observers:{
    '_rgb.r,_rgb.g,_rgb.b':function(r,g,b){
      this.setData({
        fullColor:`${r}, ${g}, ${b}`
      })
    }
    // '-_rgb.**':function(obj){
    //   this.setData({
    //     fullColor:`${obj.r}, ${obj.g}, ${obj.b}`
    //   })
    // }
  },
  methods: {
    changeR() {
      this.setData({
        '_rgb.r': this.data._rgb.r + 5 > 255 ? 255 : this.data._rgb.r + 5
      })
    },
    changeG() {
      this.setData({
        '_rgb.g': this.data._rgb.g + 5 > 255 ? 255 : this.data._rgb.g + 5
      })
    },
    changeB() {
      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)
        }
      })
    }
  },
  lifetimes:{
    created(){console.log('created');},
    attached(){console.log('attached');}
  },
  pageLifetimes:{
    show(){
      console.log('show');
      this._randomColor()
    },
    hide(){console.log('hide');},
    resize(){console.log('resize');},
  }
})
/* components/test/test.wxss */
.colorBox{
  line-height: 200rpx;
  font-size: 24rpx;
  color: white;
  text-shadow: 0rpx 0rpx 2rpx black;
  text-align: center;
}

app.json中全局引用

  "usingComponents": {
    "my-test":"/components/test/test"
  }

组件使用:

<!--pages/home/home.wxml-->
<my-test></my-test>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值