Class 与 Style 绑定

132 阅读1分钟

概述

v-bind 在用于 classstyle 时,Vue 做了专门的增强。属性的类型除了字符串以外,还可以是对象或数组。

Class

字符串:

<template>
  <div :class="className"></div>
</template>

<script>
export default {
  data () {
    return {
      className: "list-wrap"
    }
  }
}
</script>

对象:

传入一个对象,动态切换 Class。对象中的 key 就是类名,value 则是表达式。只有表达式为真时该类名才会添加到元素上。

<template>
  <div :class="{ bgc: true, 'list-wrap': false }"></div>
</template>

数组:

Class列表:

<template>
  <div :class="['box', className]"></div>
</template>

<script>
export default {
  data () {
    return {
      className: "list-wrap"
    }
  }
}
</script>

通过三元表达式动态切换:

<template>
  <div :class="[ isOk ? 'box': className]"></div>
</template>

<script>
export default {
  data () {
    return {
      className: "list-wrap",
      isOk: true
    }
  }
}
</script>

数组包含对象:

<template>
  <div :class="['box', { 'list-wrap': true, bgc: true }]"></div>
</template>

Style

字符串:

<template>
  <div style="text-align: center; font-size: 16px">Hello,Vue!</div>
</template>

对象:

对象的属性名可以用 驼峰短横线分隔(记得用引号包裹) 的方式命名。

<template>
  <div 
    :style="{ 
      'text-align': 'center', 
      fontSize: '16px' 
    }"
  >
    Hello,Vue!
  </div>
</template>

数组:

数组方式可以绑定多个样式对象。

<template>
  <div 
    :style="[
      { 
        'text-align': 'center', 
        fontSize: '16px' 
      },
      {
        color: 'tomato'
      }
    ]"
  >
    Hello,Vue!
  </div>
</template>

添加前缀

v-bind:style 使用需要添加浏览器前缀时,Vue 会自动侦测并添加相应的前缀。