1.class样式绑定的方式
1)使用v-bind
2) 使用驼峰写法
3)class对象写法,class数组写法,表达式方式的写法
<template>
<div>
<div :class="{ red: isRed, yellow: isYellow }">1.class对象写法</div>
<div :class="[red, yellow]">2.class数组写法</div>
<div :class="[
type ? 'el-button--' + type : '',
buttonSize ? 'el-button--' + buttonSize : '',
{
'is-round1': round
}
]"
> class数组与对象结合写法参考element的button组件</div>
<div :class="isRed ? 'red' : ''">3.表达式方式的写法</div>
<!-- 点击当前元素高亮,其他元素去除样式 -->
<ul>
<li v-for="(item,index) in list" :key="index" @click="click(index)" :class="{red:index===current}">
{{item}}
</li>
</ul>
</div>
</template>
<script type="text/ecmascript-6">
export default {
data() {
return {
// class对象
isRed: true,
isYellow: true,
// class数组
red: 'red',
yellow: 'yellow',
// 注意style样式写法,在js内部也可以修改这里的值
styleDate: {
fontSize:'24px',
color:'red',
backgroundColor:'pink'
},
list: [1,,2,3],
current: ''
}
},
methods: {
click(index) {
this.current = index
},
// js内部能修改值
change () {
this.styleDate.color = 'green'
}
},
}
</script>
<style lang="scss" scoped>
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
</style>
2.style样式绑定
<template>
<div>
<div
id="checkShow"
:style="{ backgroundColor: isScreen ? '#061123' : '' }"
>1.对象绑定</div>
<div :style="styleDate" @click="change">1.style写法,点击变色</div>
<ul>
<li
class="loop-item"
@click="
handleClick((currentIndex = item))
"
:style="{
background:
'url(' +
(index == currentIndex
? '../../static/img/web/nav_des_bg.png'
: '') +
') no-repeat',
}"
v-for="item in 4"
>
2.style三目运算,v-for循环的标签添加背景图片并高亮
</li>
</ul>
<div v-bind:style="{ color: textColor, fontSize: fontSize + 'px' }">
这是一个示例文本。
</div>
</div>
</template>
<script type="text/ecmascript-6">
export default {
data() {
return {
isScreen:true,
textColor: 'red',
fontSize: 16
// 注意style样式写法,在js内部也可以修改这里的值
styleDate: {
fontSize:'24px',
color:'red',
backgroundColor:'pink'
},
list: [1,,2,3],
current: '',
currentIndex: 1,
}
},
methods: {
click(index) {
this.current = index
},
// js内部能修改值
change () {
this.styleDate.color = 'green'
},
handleClick(index) {
console.log(index);
this.currentIndex = index;
},
},
}
</script>
<style lang="scss" scoped>
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
</style>
style样式绑定高级案例
参考写法::style="'height:'+(height?((height-419)+'px'):'calc(100vh - 519px)')"
根据不同的数值展示颜色
<template>
<div class="war">
<div class="con" :style="'backgroundColor:'+ getColor(5)">test</div>
</div>
</template>
<script>
function getColor(level) { //根据水质获取对应颜色
let color = "#7d7d7d"
switch (level * 1) {
case 0:
color = "#7d7d7d"
break;
case 1:
case 2:
case 3:
color = "#2ad795"
break;
case 4:
color = "#c0ce1e"
break;
case 5:
color = "#ce6131"
break;
case 6:
color = "#c70606"
break;
}
return color
}
export default {
data() {
return {
}
},
computed: {
getColor() {
return getColor
}
},
}
</script>
<style>
.con {
width: 50px;
height: 50px;
}
</style>
效果图:
getColor(5)
getColor(2)