First, the class attribute binding
Class and style are attributes of HTML elements, which are used to set the style of the element. You can use v-bind to set the style attribute.
Vue.js v-bind specifically enhances it when dealing with classes and styles. The result type of the expression can be an object or an array in addition to a string.
v-bind:class
Set an object for to switch dynamicallyclass
.active{
width:100px;
height: 100px;
background-color: lightblue;
}
<div id='app'>
<div :class="{'active' : isActive}"></div>
</div>
var vm = new Vue({
el: '#app',
data: {
isActive: true
}
})
The above example div class is:
<div class="active"></div>
- Directly bind an object in the data
.active{
width:100px;
height: 100px;
background-color: lightblue;
}
.text-danger {
background: red;
}
<div id='app'>
<div :class="classObject"></div>
</div>
var vm = new Vue({
el: '#app',
data: {
classObject: {
active: true,
'text-danger': true
}
}
})
The above example div class is:
<div class="active text-danger"></div>
- Array syntax:
数组
pass tov-bind
.active{
width:100px;
height: 100px;
background-color: lightblue;
}
.text-danger {
background: red;
}
<div id='app'>
<div v-bind:class="[activeClass, errorClass]"></div>
</div>
var vm = new Vue({
el: '#app',
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
})
The above example div class is:
<div class="active text-danger"></div>
Second, style (inline style)
v-bind:style
Set styles directly in
<div id='app'>
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' } ">Hello vue!</div>
</div>
var vm = new Vue({
el: '#app',
data: {
activeColor: 'green',
fontSize: 30
}
})
- Bind directly to a style object to make the template clearer
<div id='app'>
<div v-bind:style="styleObject">Hello vue!</div>
</div>
var vm = new Vue({
el: '#app',
data: {
styleObject:{
color: 'green',
fontSize: '30px'
}
}
})
v-bind:style
Multiple style objects can be applied to an element using an array
<div id='app'>
<div v-bind:style="[styleObject1, styleObject2]">Hello vue! </div>
</div>
var vm = new Vue({
el: '#app',
data: {
styleObject1:{
color: 'green',
fontSize: '30px'
},
styleObject2:{
'font-weight': '20'
}
}
})
Third, realize the dynamic adjustment of fonts
<div id='app'>
<div v-bind:style="{color: 'red', fontSize: size + 'px'}">可以动态调节</div>
<div v-bind:style="computedStyle">可以动态调节</div>
<div v-bind:style="objectStyle">可以动态调节</div>
<div v-bind:style="methodStyle()">可以动态调节</div>
{
{
size}}
<button @click="++size">+</button>
<button @click="--size">-</button>
</div>
var vm = new Vue({
el: '#app',
data: {
size:20,
objectStyle:{
color:'green',
fontSize: 20 + 'px'
}
},
methods:{
methodStyle: function(){
return {
color: 'green',fontSize: this.size + 'px'}
}
},
computed:{
computedStyle: function(){
return {
color: 'red', fontSize: this.size + 'px'}
}
},
watch:{
size: function(){
this.objectStyle.fontSize = this.size + 'px'
}
}
})
不积跬步无以至千里 不积小流无以成江海