在使用uniapp編寫功能時(shí),可以通過(guò)computed方法來(lái)實(shí)現(xiàn)根據(jù)num這個(gè)值也可以是后端傳過(guò)來(lái)的值只要是number類型都可以。不同取值來(lái)修改盒子的背景顏色和字體顏色。首先,在data中定義一個(gè)num來(lái)存儲(chǔ)當(dāng)前的值,然后在computed中創(chuàng)建一個(gè)樣式對(duì)象,并根據(jù)num的取值來(lái)設(shè)置相應(yīng)的背景顏色和字體顏色。
<template>
<view>
<view class="box" :style="boxStyle">{{ num }}</view>
</view>
</template>
<script>
export default {
data() {
return {
num: 1 // 默認(rèn)值為1
};
},
computed: {
boxStyle() {
let backgroundColor = "";
let color = "";
// 根據(jù)num的取值來(lái)設(shè)置樣式
switch (this.num) {
case 1:
backgroundColor = "red";
color = "lightcoral";
break;
case 2:
backgroundColor = "blue";
color = "lightblue";
break;
case 3:
backgroundColor = "green";
color = "lightgreen";
break;
default:
break;
}
// 返回樣式對(duì)象
return {
backgroundColor,
color
};
}
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
}
</style>
我們?cè)趖emplate中設(shè)置了一個(gè)名為box的view來(lái)作為盒子容器,通過(guò):style
綁定boxStyle來(lái)設(shè)置盒子的樣式。在computed中,我們創(chuàng)建了一個(gè)boxStyle方法,根據(jù)num的不同取值來(lái)設(shè)置backgroundColor和color的值,并將它們作為樣式對(duì)象返回。最后,在style中設(shè)置box的樣式,如寬度、高度、居中等。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-717410.html
這樣,當(dāng)num的值改變時(shí),盒子的背景顏色和字體顏色就會(huì)隨之變化。就不需要使用v-if設(shè)置多個(gè)盒子和多個(gè)樣式。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-717410.html
到了這里,關(guān)于css:如何通過(guò)不同的值,改變盒子的樣式和字體顏色通過(guò)computed而不是v-if的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!