自定义组件的.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;
}