美文网首页
绑定Class

绑定Class

作者: _白羊 | 来源:发表于2018-10-16 18:50 被阅读11次

注意:Class 与 Style 绑定:
1、使用 (v-bind:表达式结果) 进行实现
2、在将 v-bind 用于 class 和 style 时,表达式结果的类型除了字符串之外,还可以是对象或数组

绑定 HTML Class

对象语法

(1)内联定义在模板

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

// JS
data: {
  isActive: true,
  hasError: false
}

// 渲染结果
<div class="static active"></div>

(2)不内联定义在模板内

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

// JS
data: {
  classObject: {
    active: true,
    'text-danger': false
  }

// 渲染结果
<div class="static active"></div>
}

(3)通过计算属性实现

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

// JS
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

数组语法
(1)一个数组传给 v-bind:class

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

// JS
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

// 渲染结果
<div class="active text-danger"></div>

(2)根据条件切换列表中的 class,可以用三元表达式

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

(3)在数组语法中使用对象语法:

<div v-bind:class="[{ active: isActive }, errorClass]"></div>

用在组件上
注意:当在一个自定义组件上使用 class 属性时,这些类将被添加到该组件的根元素上面。这个根元素上已经存在的类不会被覆盖。
例如,如果你声明了这个组件:

// JS
Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})

// html
<my-component class="baz boo"></my-component>
<my-component v-bind:class="{ active: isActive }"></my-component>

// 渲染结果
<p class="foo bar baz boo">Hi</p>
//当 `isActive` 为 truthy时
<p class="foo bar active">Hi</p>


相关文章

网友评论

      本文标题:绑定Class

      本文链接:https://www.haomeiwen.com/subject/fitkzftx.html