Vue CSS 绑定

了解有关如何使用的更多信息v-bind修改 CSS 为styleclass属性。

观念转变的同时styleclass属性与v-bind相当简单,语法可能需要一些时间来适应。

Vue 中的动态 CSS

您已经了解了如何使用 Vue 来修改 CSSv-bindstyleclass属性。本教程已对此进行了简要解释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:classv-bind:style我们之前在本教程中没有见过:

  1. 当 CSS 类被分配给 HTML 标签时class=""v-bind:class=""Vue 合并了类。
  2. 包含一个或多个类的对象被分配为v-bind:class="{}"。在对象内部,可以打开或关闭一个或多个类。
  3. 具有内联样式(v-bind:style) 定义 CSS 属性时,首选驼峰命名法,但如果将其写在引号内,也可以使用“kebab-case”。
  4. CSS 类可以使用数组/数组符号/语法进行分配

下面将更详细地解释这些要点。


1.Vue 合并 'class' 和 'v-bind:class'

当 HTML 标签属于指定的类时class="",并且还被分配到一个类v-bind:class="",Vue 为我们合并了类。

示例

<div>元素属于两个类:“impClass”和“yelClass”。 “重要”类以正常方式设置class属性,并且“黄色”类设置为v-bind:class

<div class="impClass" v-bind:class="{yelClass: isYellow}">
  This div belongs to both 'impClass' and 'yelClass'.
</div>
亲自试一试 »

2. 使用“v-bind:class”分配多个类

将 HTML 元素分配给类时v-bind:class="{}",我们可以简单地使用逗号来分隔和分配多个类。

示例

<div>元素可以属于“impClass”和“yelClass”类,具体取决于布尔 Vue 数据属性“isYellow”和“isImportant”。

<div v-bind:class="{yelClass: isYellow, impClass: isImportant}">
  This tag can belong to both the 'impClass' and 'yelClass' classes.
</div>
亲自试一试 »

3. Camel case 与 kebab case 表示法与 'v-bind:style'

当使用内联样式修改 Vue 中的 CSS 时(v-bind:style),建议对 CSS 属性使用驼峰命名法,但如果 CSS 属性在引号内,也可以使用“kebab-case”。

示例

在这里,我们设置 CSS 属性background-colorfont-weight为一个<div>元素有两种不同的方式:推荐使用驼峰命名法backgroundColor,以及不推荐的方式,在引号中包含“kebab-case”'font-weight'。两种选择都有效。

<div v-bind:style="{ backgroundColor: 'lightpink', 'font-weight': 'bolder' }">
  This div tag has pink background and bold text.
</div>
亲自试一试 »

“Camel case”和“kebab case”表示法是书写一系列没有空格或标点符号的单词的方法。

  • 骆驼香烟盒表示法是第一个单词以小写字母开头,后面的每个单词都以大写字母开头,例如“backgroundColor”或“camelCaseNotation”。之所以称为驼峰式,是因为我们可以想象每个大写字母都像骆驼背上的驼峰。
  • 烤肉串案例表示法是单词之间用破折号分隔-,如“背景颜色”或“kebab-case-notation”。它被称为烤肉串案例,因为我们可以想象像“烤肉串”中的串一样的破折号。

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>
亲自试一试 »