微信小程序——自定义组件的自增笔记

自定义组件的.wxml代码

<view>
  {{n1}}+{{n2}}={{sum}}
</view>
<button size="mini" bindtap="addN1">n1自增</button>
<button size="mini" bindtap="addN2">n2自增</button>

自定义组件的.js代码

// components/test1/test1.js
Component({
  observers:{
    'n1,n2':function(n1,n2){
      this.setData({sum:n1+n2})
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    max:{
      type:Number,
      value:20
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    n1:0,
    n2:0,
    sum:0

  },
 

  /**
   * 组件的方法列表
   */
  methods: {
    addN1(){
      if(this.data.n1>=this.properties.max)
        return wx.showToast({
          title: '加载不能超过20',
          icon:'error'
        })
      this.setData({
        n1:this.data.n1+1
      })
    },
    addN2(){
      if(this.data.n2>=this.properties.max)
        return wx.showToast({
          title: '加载不能超过20',
          icon:'error'
        })
      this.setData({
        n2:this.data.n2+1
      })
    }

  }
})

以下自定义组件的.wxml代码

<view class="colorBox" style="background-color: rgb({{fullcolor}});">
  颜色值:{{fullcolor}}
</view>
<button type="default" size="mini" bindtap="changeR">R</button>
<button type="primary" size="mini" bindtap="changeG">G</button>
<button type="warn" size="mini" bindtap="changeB">B</button>

以下自定义组件的.js代码

// components/test2/test2.js
Component({
  pageLifetimes:{
    show(){
      this._randomRgb()
    },
  },
  observers: {
    'rgb.**':function(obj){
      this.setData({
        //模板字符串
        fullcolor:`${obj.r},${obj.g},${obj.b}`
      })
    }

  },
  /**
   * 组件的属性列表
   */
  properties: {

  },


  /**
   * 组件的初始数据
   */
  data: {
    rgb:{
      r:0,
      g:0,
      b:0
    },
    fullcolor:'0,0,0'

  },

  /**
   * 组件的方法列表
   */
  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
      })
    },
    _randomRgb(){
      this.setData({
        rgb:{
          r:Math.floor(Math.random()*255),
          g:Math.floor(Math.random()*255),
          b:Math.floor(Math.random()*255),
        }
      })
    }

  }
})

以下自定义组件的.wxss代码

.colorBox{
  width: 100%;
  height: 200rpx;
  color: white;
  text-align: center;
  line-height: 200rpx;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值