- 在应用界面中,某个(些)元素的样式是变化的
- class,style绑定就是专门用来实现动态样式效果的技术
class 绑定
-
:class=‘xxx’
-
表达式是字符串: ‘classA’
-
表达式是对象: {classA:isA, classB: isB}
-
表达式是数组: [‘classA’, ‘classB’]
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>class绑定</title>
<script src="../js/vue.js"></script>
<style>
.basic{
width: 100px;
height: 100px;
}
.bgOrange{
background-color: orange;
}
.bgTeal{
background-color: teal;
}
.border{
border-style: dashed;
border-color: aqua;
border-width: 1px;
}
</style>
</head>
<body>
<div id="app">
<!-- 绑定class样式(类名不确定,动态的) -->
<!-- 字符串写法 (名字不确定)-->
<div class="basic" :class="bgColor" @click="change"></div>
<!-- 数组写法 (个数和名字不确定)-->
<div class="basic" :class="classArr"></div>
<!-- 对象写法 (个数和名字确定 但要动态决定)-->
<div class="basic" :class="classObj"></div>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
bgColor: 'bgOrange',
classArr: ['border', 'bgTeal'],
classObj: {
bgOrange: true,
border: false
}
};
},
methods: {
change(){
this.bgColor = this.bgColor == 'bgOrange' ? 'bgTeal' : 'bgOrange';
}
},
})
</script>
</body>
style 绑定
<body>
<div id="app">
<!-- 绑定style样式 -->
<div class="basic" :style="{fontSize: fsize + 'px'}">
绑定style样式
</div>
<div class="basic" :style="styleObj">
对象写法
</div>
<div class="basic" :style="styleArr">
数组对象写法
</div>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
bgColor: 'bgOrange',
fsize: 20,
styleObj:{
color: 'red'
},
styleArr:[{color: 'red'}, {fontSize: '20px'}]
};
}
})
</script>
</body>