动态样式绑定
动态样式绑定
一般来讲样式直接通过class和style属性直接写在元素上了,但是也经常会有动态样式这样的需求。比如我们需要切换字体颜色:
<template>
<div>
<p class="font-lg" :class="currentColor">我是文字</p>
<button @click="changeColor('green-color')">变成绿色</button>
<button @click="changeColor('red-color')">变成红色</button>
</div>
</template>
<script>
export default {
data(){
return {
currentColor:'red-color',
}
},
methods:{
changeColor(colorClass){
this.currentColor = colorClass
}
}
}
</script>
<style>
.red-color {
color: red;
}
.green-color {
color:green;
}
.font-lg{
font-size: 40px;
}
</style>
这时候的代码相比之前稍微复杂一些,其实还是v-bind。如果你想直接绑定style字符串也是可以的
<p :style="'color:red'">我是文字</p>
除了通过字符串的方式进行绑定样式外,vue还支持通过对象的方式绑定,不管是哪种方式绑定,class可以和:class共存,并且vue会自己合并,style也同样如此。对象方式平时我用的比较少。这里不展开了。想要了解的可以去查看官方手册。
本文系作者 @迦娜王 原创发布在 松鼠乐园。未经许可,禁止转载。