v-bind属性绑定为元素设置class类样式和style行内样式
【在VUE中对样式的设置】
一、class样式
<style> .red { color: red; } .thin{ font-weight: 200; /* 字体细瘦 */ } .active { letter-spacing: 0.5em; /* 字符间隔 */ /* word-spacing只针对英文,不支持中文 */ } </style>
1. 直接传递一个数组
<h1 :class="['red','thin']">这是又红又瘦的h1</h1>
将样式名称以字符串的形式传入。
若不以字符串形式,如[thin],则会视为变量在data中寻找,而data中没有,故会报错。
2. 数组中使用三元表达式
<h1 :class="['red','thin',flag?'active':'']">这是又红又瘦又变化的h1</h1>
data: { flag: true }
根据flag的状态判断active是否被激活。
3. 数组中使用对象代替三元表达式,提高代码可读性
<h1 :class="['red','thin',{'active':flag}]">这是又红又瘦又变化的h1</h1>
data: { flag: true }
在数组中写对象,属性是类名。
4. 绑定对象
<h1 :class="{ red: true, thin: true, active: false }">这是又红又瘦间距又小的h1</h1>
或
<h1 :class="classObj">这是又红又瘦间距又小的h1</h1>
data: { classObj: { red: true, thin: true, active: false } }
对象的属性是类名,对象的值是标识符。
属性名可带引号也可不带。
二、内联样式
1. 直接在元素上使用:style
<h1 :style="{ color: 'red', 'font-weight':200}">这是又红又瘦的h1</h1>
当属性名包含“-”等时,必须加引号。
2. 将样式对象定义到data中,并引用
<h1 :style="styleObj">这是又红又瘦的h1</h1>
data: { styleObj: { color: 'red', 'font-weight':200} }
3. 通过数组,引用多个data上的样式对象
<h1 :style="[styleObj1, styleObj2]">这是又红又瘦又斜的h1</h1>
data: { styleObj1: { color: 'red', 'font-weight':200}, styleObj2: { 'font-style': 'italic' }
}

浙公网安备 33010602011771号