Class and style binding in Vue
1. Class binding
<style>
div{
width: 300px;
height: 300px;
}
.red{
background-color: brown;
}
.yellow{
background-color: chartreuse;
}
.border{
border: 1px solid #000;
}
</style>
<div id="app">
<div v-bind:class='{red:flag}'></div>
</div>
<script>
new Vue({
el:"#app",
data:{
flag:true/false
}
})
</script>
2. Class is used as an object to bind multiple style styles
Recommended in the development process
<div id="app">
<div v-bind:class='classObj'></div>
</div>
<script>
new Vue({
el:"#app",
data:{
classObj:{
red:true,
border:true,
radius:true
}
}
})
</script>
div{
width: 300px;
height: 300px;
}
.red{
background-color: brown;
}
.yellow{
background-color: chartreuse;
}
.border{
border: 1px solid #000;
}
.radius{
border-radius:50%;
}
3. Process by calculating attributes
Realization of calculated attributes (writing method):
computed:{
Variable name: function(){
return expression
}
}
is equivalent to
computed:{
Variable name () {
return expression
}
}
<div id="app">
<!-- <div v-bind:class='classObj'></div> -->
<div v-bind:class='computerClass'></div>
</div>
<script>
new Vue({
el:"#app",
data:{
classObj:{
red:true,
border:true,
radius:true
},
class1:{
yellow:true,
border:true
},
red:true,
border:true
},
computed:{
computerClass(){
return{
red:this.red && this.border
}
}
}
})
4. Class array syntax
<div id="app">
<div v-bind:class='[c1,c2]'>大唐芙蓉园</div>
</div>
<script>
new Vue({
el:"#app",
data:{
c1:'green',
c2:'border'
}
})
</script>
<style>
div{
width: 100px;
height: 100px;
}
.green{
background-color: rgb(97, 211, 97);
color: cornsilk;
}
.border{
border: 1px solid black;
}
</style>
5. Style object binding
<div id="app">
<div v-bind:style='{
color:activeColor,fontSize:fontsize+"px"}'>大唐芙蓉园</div>
<div v-bind:style="{
color:yellow,fontSize:fontsize1}">大唐芙蓉园</div>
<div v-bind:style="styleClass">回民街</div>
</div>
<script>
new Vue({
el:"#app",
data:{
activeColor:"red",
fontsize:30,
yellow:"yellow",
fontsize1:'30px',
styleClass:{
color:"blue",
fontSize:"30px",
backgroundColor:"#ccc"
}
}
})
</script>
6. Calculate attribute binding style
<div id="app">
<div v-bind:style="computerClass">大唐芙蓉园</div>
</div>
<script>
new Vue({
el:"#app",
data:{
b1:false/true
},
computed:{
computerClass(){
return{
color:this.b1?"red":"green",
fontSize:this.b1?"20px":"30px",
fontWeight:this.b1?"bold":"normal"
}
}
}
})
</script>
<div id="app">
<div v-bind:style='[styleObj1,styleObj2]'>大唐芙蓉园</div>
</div>
<script>
new Vue({
el:"#app",
data:{
styleObj1:{
color:"white"
},
styleObj2:{
textAlign:"center",
lineHeight:"100px"
}
}
})
</script>