1.style属性绑定
通过v-bind进行属性绑定,引号里面是js语法,因为style属性值是 键值对的形式,所以我们这里用对象的形式来表示。(Vue2中)
<template>
<view>
<view class="box" :style="{backgroundColor:randomcolor}" @click="randomColor">点击一下颜色随机变化</view>
</view>
</template>
<script>
export default {
data() {
return {
randomcolor:'pink',
}
},
methods:{
randomColor(){
let arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
let randomStrArr = [];
for(let i=0;i<=5;i++){
randomStrArr[i] = arr[Math.floor(Math.random()*arr.length)];
}
this.randomcolor = `#${randomStrArr.join("")}`;
}
// randomColor(){
// let r = Math.floor(Math.random()*256);
// let g = Math.floor(Math.random()*256);
// let b = Math.floor(Math.random()*256);
// this.randomcolor = `rgb(${r},${g},${b})`
// }
}
}
</script>
<style lang="scss">
.box{
width: 200rpx;
height: 200rpx;
}
</style>
2.随机颜色生成
01.十六进制的方式
randomColor(){
let arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
let randomStrArr = [];
for(let i=0;i<=5;i++){
randomStrArr[i] = arr[Math.floor(Math.random()*arr.length)];
}
this.randomcolor = `#${randomStrArr.join("")}`;
}
02.rgb的形式
randomColor(){
let r = Math.floor(Math.random()*256);
let g = Math.floor(Math.random()*256);
let b = Math.floor(Math.random()*256);
this.randomcolor = `rgb(${r},${g},${b})`
}
3.class属性绑定
<template>
<view>
<!-- <view class="block" :class="{myactive:state}" @click="changeBgc">点我就变</view> -->
<view class="block" :class="state ? 'myactive':''" @click="changeBgc">点我就变</view>
</view>
</template>
<script>
export default {
data() {
return {
state:true,
}
},
methods:{
changeBgc(){
this.state = !this.state;
}
}
}
</script>
<style lang="scss">
.block{
width: 200rpx;
height: 200rpx;
background-color: #ccc;
}
.myactive{
width: 400rpx;
height: 400rpx;
background-color: pink;
border-radius: 5%;
}
</style>