一、用微信小程序原生的写法
<view class="box" style="background:{{bgcolor}}" bind:tap="changecolor">
{{num}}
</view>
Page({
/**
* 页面的初始数据
*/
data: {
num:0,
bgcolor: "#00c"
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.changecolor(),
},
changecolor() {
let num =parseInt(Math.random() * 100);
let r = parseInt(Math.random() * 255);
let g = parseInt(Math.random() * 255);
let b = parseInt(Math.random() * 255);
let color = ` rgb(${r},${g},${b})`;
console.log(color);
console.log(num);
this.setData({
bgcolor:color,
num:num
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
}
.box {
width: 100rpx;
height: 100rpx;
color: #fff;
text-align: center;
line-height: 100rpx;
}
二、uniapp 用vue的写法
<<template>
<view>
<view class="box" v-bind:style="{background:bgcolor}" v-on:click="changecolor">
{{num}}
</view>
</view>
</template>
<script>
export default {
data() {
return {
bgcolor: "#00c",
num: 1,
}
},
methods: {
changecolor() {
let num =parseInt(Math.random() * 100);
let r = parseInt(Math.random() * 255);
let g = parseInt(Math.random() * 255);
let b = parseInt(Math.random() * 255);
let color = ` rgb(${r},${g},${b})`;
console.log(color);
console.log(num);
this.bgcolor = color;
this.num=num
}
}
}
</script>
<style lang="scss">
.box {
width: 100rpx;
height: 100rpx;
color: #fff;
text-align: center;
line-height: 100rpx;
}
</style>