Vue.js 样式绑定

Vue.js 教程 · 2019-04-02 15:39:14

Vue.js class

class 与 style 是 HTML 元素的属性,用于设置元素的样式,我们可以用 v-bind 来设置样式属性。

Vue.js v-bind 在处理 class 和 style 时, 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。

class 属性绑定

我们可以为 v-bind:class 设置一个对象,从而动态的切换 class:

实例 1

实例中将 isActive 设置为 true 显示了一个绿色的 div 块,如果设置为 false 则不显示:

<div v-bind:class="{ active: isActive }"></div>

以上实例 div class 为:

<div class="active"></div>

我们也可以在对象中传入更多属性用来动态切换多个 class 。

实例 2

text-danger 类背景颜色覆盖了 active 类的背景色:

<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"> </div>

以上实例 div class 为:

<div class="static active text-danger"></div>

我们也可以直接绑定数据里的一个对象:

实例 3

text-danger 类背景颜色覆盖了 active 类的背景色:

<div id="app"> <div v-bind:class="classObject"></div> </div>

实例 3 与 实例 2 的渲染结果是一样的。

此外,我们也可以在这里绑定返回对象的计算属性。这是一个常用且强大的模式:

实例 4

new Vue({ el: '#app', data: { isActive: true, error: { value: true, type: 'fatal' } }, computed: { classObject: function () { return { base: true, active: this.isActive && !this.error.value, 'text-danger': this.error.value && this.error.type === 'fatal', } } } })

数组语法

我们可以把一个数组传给 v-bind:class ,实例如下:

实例 5

<div v-bind:class="[activeClass, errorClass]"></div>

以上实例 div class 为:

<div class="active text-danger"></div>

我们还可以使用三元表达式来切换列表中的 class :

实例 6

errorClass 是始终存在的,isActive 为 true 时添加 activeClass 类:

<div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>

Vue.js style(内联样式)

我们可以在 v-bind:style 直接设置样式:

实例 7

<div id="app"> <div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">码农教程</div> </div>

以上实例 div style 为:

<div style="color: green; font-size: 30px;">码农教程</div>

也可以直接绑定到一个样式对象,让模板更清晰:

实例 8

<div id="app"> <div v-bind:style="styleObject">码农教程</div> </div>

v-bind:style 可以使用数组将多个样式对象应用到一个元素上:

实例 9

<div id="app"> <div v-bind:style="[baseStyles, overridingStyles]">码农教程</div> </div>

注意:当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform ,Vue.js 会自动侦测并添加相应的前缀。

点击查看所有 Vue.js 教程 文章: https://www.codercto.com/courses/l/38.html

查看所有标签

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具