v-bind 的class+style的绑定

2019-03-09  本文已影响0人  5吖

一、绑定 Class

1、对象语法

v-bind:class 设置为一个对象,动态地切换 class,其中对象的键名是类名,值为布尔值 true 或 false

<div v-bind:class="{ active: isActive }"></div> // active存在取决isActive的值

1.1、 绑定数据对象不必定义在模板内

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

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

1.2、 绑定一个计算属性,可以使用 datacomputed

data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}
2、数组语法

把一个数组传给 v-bind:class,以应用一个 class 列表,数组成员直接对应className类名

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

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

【Demo 实例 https://jsbin.com/honegiv/edit?html,output

3、数组和对象混用
<div v-bind:class="[{ active: isActive }, errorClass]"></div> // 这样写始终添加 errorClass

【Demo 实例 https://jsbin.com/desibet/edit?html,output

二、绑定 内联 Style

v­-bind:style (即:style ) 给元素绑定内联样式

注:CSS 属性名可以用驼峰式 (camelCase)短横线分隔 (kebab-case,记得用单引号括起来) 来命名

1、对象语法
//html
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

//js
data: {
  activeColor: 'red',
  fontSize: 30
}
2、数组语法

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

<div v-bind:style="[baseStyles, overridingStyles]"></div>

使用 :style 时, Vue .js 会自动给特殊的 css 属性名称增加前缀, 比如 transform

【demo 实例 https://jsbin.com/qapozop/6/edit?html,output

上一篇 下一篇

猜你喜欢

热点阅读