Vue CSS 绑定
学习更多关于如何使用 v-bind
修改具有 style
和 class
属性的 CSS 的信息。
虽然用 v-bind
更改 v-bind
修改具有 style
和 class
属性的概念相当简单,但语法可能需要一些习惯。
Vue 中的动态 CSS
您已经了解了如何使用 Vue 通过在样式和类属性上使用 v-bind
来修改 CSS。本教程在 v-bind
下对其进行了简要解释,并给出了几个 Vue 更改 CSS 的例子。
在这里,我们将更详细地解释如何使用 Vue 动态更改 CSS。但是,首先让我们看两个例子,使用我们在本教程中已经看到的技术:使用 v-bind:style
的内联样式和使用 v-bind:class
。
内联样式
我们使用 v-bind:style
在 Vue 中进行内联样式。
实例
<input type="range">
元素用于通过使用内联样式来更改 <div>
元素的不透明度。
<input type="range" v-model="opacityVal">
<div v-bind:style="{ backgroundColor: 'rgba(155,20,20,'+opacityVal+')' }">
Drag the range input above to change opacity here.
</div>
样式表赋值
我们使用 v-bind:class
为 Vue 中的 HTML 标记赋值一个样式表。
实例
选择食物的图片。使用 v-bind:class
突出显示所选食物,以显示您所选的食物。
<div v-for="(img, index) in images">
<img v-bind:src="img.url"
v-on:click="select(index)"
v-bind:class="{ selClass: img.sel }">
</div>
其他赋值样式表或样式的方法
以下是关于 v-bind:class
和 v-bind:style
的使用的不同方面,我们以前在本教程中从未见过:
- 当 CSS 样式类被分配给同时具有
class=""
和v-bind:class=""
的 HTML 标记时,Vue 会合并这些样式类。 - 包含一个或多个类的对象被赋值为
v-bind:class="{}"
。在对象内部,可以打开或关闭一个或多个样式类。 - 使用内联样式(
v-bind:style
),在定义 CSS 属性时,首选 camelCase 驼峰式,但如果 'kebab-case' 写在引号内,也可以使用。 - CSS 类可以用数组/用数组表示法/语法进行赋值。
以下将更详细地解释这些要点。
1. Vue 合并 'class' 和 'v-bind:class'
如果 HTML 标记属于用 v-bind:class=""
赋值样式表,并且也被赋值给 v-bind:class=""
的类,Vue 会为我们合并这些样式类。
实例
v-bind:class="{}"
元素属于两个类:'impClass' 和 'yelClass'。
"important" 样式类用 class
属性以正常方式设置,"yellow" 类用 v-bind:class
设置。
<div class="impClass" v-bind:class="{yelClass: isYellow}">
This div belongs to both 'impClass' and 'yelClass'.
</div>
2. 使用 'v-bind:class' 赋值多个样式表
当用 v-bind:class="{}"
将 HTML 元素分配一个样式类时,我们可以简单地使用逗号来分隔和分配多个类。
实例
根据布尔 Vue 数据属性 'isYellow' 和 'isImportant',<div>
元素可以同时属于 'impClass' 和 'yelClass' 类。
<div v-bind:class="{yelClass: isYellow, impClass: isImportant}">
This tag can belong to both the 'impClass' and 'yelClass' classes.
</div>
3. 使用 'v-bind:style' camelCase 驼峰对比 kebab case
在 Vue 中使用内联样式(v-bind:style
)修改 CSS 时,建议对 CSS 属性使用 camelCase 表示法,但如果 CSS 属性位于引号内,也可以使用 kebab-case。
实例
在这里,我们用两种不同的方式为 <div>
元素设置 CSS 属性 background-color
和 font-weight
:推荐使用 camelCase backgroundColor
的方式,不推荐使用引号中的 'kebab-case' 的方式。两种选择都有效。
<div v-bind:style="{ backgroundColor: 'lightpink', 'font-weight': 'bolder' }">
This div tag has pink background and bold text.
</div>
4. 带有 v-bind:class 的数组语法
我们可以使用数组语法和 v-bind:class
来添加多个样式类。使用数组语法,我们既可以使用依赖 Vue 属性的类,也可以使用不依赖 Vue 特性的样式类。
实例
在这里,我们用数组语法设置 CSS 类 'impClass' 和 'yelClass'。类 'impClass' 依赖于 Vue 属性 isImportant
,类 'yelClass' 始终附加到 <div>
元素。
<div v-bind:class="[{ impClass: isImportant }, 'yelClass' ]">
This div tag belongs to one or two classes depending on the isImportant property.
</div>