bind class
object syntax
We can pass v-bind:class
an object to dynamically switch classes. Note that v-bind:class
directives can class
coexist with common features:
例如:<div class="static" v-bind:class="{ 'class-a': isA, 'class-b': i%2===0}"></div>
If isA=true, class-a is bound; where i%2===0 means that the type and value must be exactly the same, and i%2==0 means that the value is equal
array syntax
<div v-bind:class="[classA, classB]">
data:{
classA: 'class-a',
classB: 'class-b'
}
渲染为:<div class="class-a class-b"></div>
You can also use the ternary operator:
<div v-bind:class="[classA, isB ? classB : '']">
Objects can be used in arrays:
<div v-bind:class="[classA, { classB: isB, classC: isC }]">
If isB=true, the result is <div class="classA classB">
Binding inline styles
v-bind:style
's object syntax is very intuitive - it looks a lot like CSS, but it's actually a JavaScript object. CSS property names can be named in camelCase or kebab-case:
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
Binding directly to a style object is usually better and makes the template clearer:
<div v-bind:style="styleObject"></div>
data: { styleObject: { color: 'red', fontSize: '13px' } }v-bind:style
array syntax to apply multiple style objects to an element
<div v-bind:style="[styleObjectA, styleObjectB]">