您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页绑定Class

绑定Class

来源:二三娱乐

注意: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'
    }
  }
}
// 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>
// JS
 {
  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>


Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务