Appearance
对象语法
本节目标:理解“对象语法”的核心思路,并能把它用于实际开发或面试表达。 一、当要为元素设置多个样式
(class)时,可以设置元素v-bind:class的值为一个对象。此时,对象的键名代表样式名,而键值是否为真控制着样式是否生效。即键值为turth值时,这个键名所代表样式就生效,否则键名所代表的样式不生效。
这样就可以通过控制键值来控制样式。如:
<div v-bind:class="{ active: isActive }"></div>上面active 这个 class 存在将取决于数据 property isActive 的
truthiness。
二、v-bind:class 绑定的样式不会覆盖普通的 class attribute样式。当有如下模板:
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>和如下 data:
data: { isActive: true, hasError: false}结果渲染为:
<div class="static active"></div>三、绑定的数据对象不必内联定义在模板里:
<div v-bind:class="classObject"></div>
data: { classObject: { active: true, 'text-danger': false }}渲染的结果和上面一样。
四、绑定计算属性:可以绑定一个返回对象的计算属性。这是一个常用且强大的模式:
<div v-bind:class="classObject"></div>
data: { isActive: true, error: null},computed: { classObject: function () { return { active: this.isActive && !this.error, 'text-danger': this.error && this.error.type === 'fatal' } }}