Vue动态样式
背景:在我们的前端界面中,很多的地方的样式都是不确定的状态,要根据其他内容的变化而变化样式的。本文总结一下自己用到的动态样式方法。
一、动态绑定 :style
👉1.使用对象方式
通过v-bind:style来绑定style样式,“”引号里面使用对象的方式,为key,value形式,key值为css属性名,注意的是例如font-size,在key中要写成fontSize驼峰命名规则。value就是我们绑定的值,可以动态去改变。
<h1 :style="{ color: Color ,fontSize:size+'px'}">浪漫主义码农</h1>
例子:
<template><div><h1 :style="{ color: Color ,fontSize:size+'px'}">浪漫主义码农</h1><div class="btn"><el-button type="primary" @click="changeColor">点击切换颜色</el-button><el-button type="primary" @click="Change_size">字体变大</el-button></div></div>
</template>
<script> export default {data() {return {Color:'blue',size:14};},methods:{changeColor(){this.Color='red'},Change_size(){this.size++}}
}; </script>
也可以将所有的属性全部写在一个对象里面,最后在:style绑定这个对象就行,简化页面代码
例如:
<template><div><h1 :style="myStyle">浪漫主义码农</h1></div>
</template>
<script> export default {data() {return {myStyle: {fontSize: 40 + "px",color: "red",},};},
}; </script>

👉2.使用三目表达式
通过布尔表达式来判断value值应该为什么,ifcolor为表达式,并使用圆括号将三目表达式包起来
<h1 :style="{ color:(ifcolor?'red':'blue')">浪漫主义码农</h1>

👉3.使用数组方式
:style=“[{样式对象1},{样式对象2},…]”
可以将多组样式对象应用到同一个元素上,但是如果有css属性相同,则后面的样式会覆盖前面的。
例子:

<template><div><h1 :style="[styles1,styles2]">浪漫主义码农</h1></div>
</template>
<script> export default {data() {return {styles1: {backgroundColor: "red","width": "300px",},styles2: {color: "#fff",height: "300px",}};},
}; </script>
二、动态绑定 :class
使用v-bind:class
👉1. 使用对象方法
:class="{类名1:布尔值1,类名2:布尔值2}"
当布尔值为true整个类生效,否则就不生效,class和:class并不冲突,因为class可以是很多个。写法也是相对的自由
例子:

<template><div><p class="class1" :class="{class2:ifcolor,class3:true}">浪漫主义码农</p></div>
</template>
<script> export default {data() {return {ifcolor:false,}},
}; </script>
<style> div{margin-left: 100px;
}
.class1{background: #E6A23C;width: 100px;height: 100px;
}
.class2{color: red;
}
.class3{font-size: 30px;font-weight: 1000;
} </style>
👉2. 使用三目表达式
我们使用三目运算符能够更加的灵活的,并简化对象方法的写法,,对象的写法我们需要一个变量去控制每一个类,使用三目运算符可以简化一点,我最常使用的是种形式。
:class="布尔值 ? '类1' : '类2'"
例子:

<template><div><h1 :class="ifcolor ? 'Red' : 'Pink'">“浪漫至死不渝,温柔绝对屈服”</h1></div>
</template>
<script> export default {data() {return {ifcolor: false,};},mounted() {setInterval(() => {this.ifcolor = !this.ifcolor;}, 1000);},
}; </script>
<style> div {margin-left: 200px;margin-top: 200px;
}
.Red {font-size: 20px;color: red;animation: big 1s;
}
.Pink {font-size: 20px;color: pink;animation: small 1s;
}
@keyframes big {0% {font-size: 20px;}100%{font-size: 30px;}
}
@keyframes small {0% {font-size: 30px;}100%{font-size: 20px;}
} </style>
👉2. 使用数组方法
和上面的style一样的使用
:class="[class1, class2]"
例子:

代码:
<template><div><p :class="[classA,classB,classC]">今天毕业拍毕业照了</p></div>
</template>
<script> export default {data(){return{classA:'one',classB:'two three',classC:'five'}}
} </script>
<style> div{margin-left: 200px;margin-top: 200px;
}
.one{background: pink;
}
.two{font-size: 30px;
}
.three{color: red;
}
.five::after{content: ",青春再见";
} </style>
最后
最近还整理一份JavaScript与ES的笔记,一共25个重要的知识点,对每个知识点都进行了讲解和分析。能帮你快速掌握JavaScript与ES的相关知识,提升工作效率。
有需要的小伙伴,可以点击下方卡片领取,无偿分享