代码示例
在需要使用组件的json页面使用
{
"usingComponents": {
"test1":"/components/test1/test1"
}
}
wxml:
<!--components/test1.wxml-->
<text>components/test1.wxml</text>
<view class="rbgColor" style="background-color: rgb({{rbgColor}})"></view>
<button bindtap="changeColor" type="primary" style="margin-top: 20rpx;">改变颜色</button>
<view>
监听当前使用的颜色:{{rbgColor}}
</view>
wxss:
.rbgColor{
width: 100%;
height: 200rpx;
text-align: center;
line-height: 200rpx;
}
组件js
// components/test1.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
r: 0,
g: 0,
b: 0,
rbgColor: '0,0,0'
},
/**
* 组件的方法列表
*/
methods: {
changeColor() {
this.setData({
r: Math.floor(Math.random() * 256),
g: Math.floor(Math.random() * 256),
b: Math.floor(Math.random() * 256)
})
}
},
observers: {
// 监听r,g,b的变化,执行这个函数
'r,g,b': function (r, b, g) {
this.setData({
rbgColor: `${r},${g},${b}`
})
}
}
})