🌗 Vue 样式绑定
在应用界面中,某个(些)元素的样式是会发生变化的。使用  class  /  style  绑定实现动态样式效果的技术。因为  class  和  style  都是 HTML 标签的特性(Attribute),所以可以通过  v-bind  绑定相应的字符串表达式。但是字符串表达式容易出错,所以还可绑定对象或者数组。
# class  列表绑定
 语法: v-bind:class="xxx" (或者简写为  :class=“xxx” ) ,有三种写法:
xxx表达式可以是字符串classA,适用于类名不确定时;xxx表达式可以是数组['classA','classB'],适用于要绑定多个样式,但是个数不确定、名字不确定;xxx表达式可以是对象:{classA:isA, classB: isB},适用于绑定多个样式,个数不确定、名字不确定、是否使用也不确定;
🌰 例子 / 绑定数组:
<div v-bind:class="[activeClass, errorClass]"></div>
 1
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}
 1
2
3
4
2
3
4
在数组中也可以根据条件切换  class :
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
 1
最好的写法还是使用对象语法。
🌰 例子 / 绑定对象,动态切换  class :
<div
  class="static"
  v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
 1
2
3
4
2
3
4
data  中的相关数据:
data: {
  isActive: true,
  hasError: false
}
 1
2
3
4
2
3
4
最后渲染的结果为:
<div class="static active"></div>1
绑定的数据对象可以不用内联定义在模版里,而是在  data  中:
data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}
 1
2
3
4
5
6
2
3
4
5
6
在模版中可以直接绑定这个对象变量即可:
<div :class="classObject">
  ... 
</div>
 1
2
3
2
3
使用  computed  计算属性,可以使得这个类对象变换更加灵活:
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}
 1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
🌰 例子 / 在 Vue 组件的  class  property 中,如果原来的元素已经存在  class  ,而在使用的时候又添加  class ,不会覆盖原来的  class  列表。
🌰 例子:
Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})
 1
2
3
2
3
<my-component class="baz boo"></my-component>
 1
最终渲染的结果为:
<p class="foo bar baz boo">Hi</p>
 1
🌰 例子 / 对于数据绑定  class  也适用:
<my-component v-bind:class="{ active: isActive }"></my-component>
 1
最终渲染结果为:
<p class="foo bar active">Hi</p>
 1
# style  内联样式绑定
 语法:  v-bind:style="xxx" (简写为  :style=“xxx” ):
xxx表达式是样式对象,可动态修改样式属性值,例如{fontSize: fontSize +‘px’};(多个单词的 CSS 样式采用驼峰命名)xxx表达式是数组,将多个样式对象同时应用在一个元素中,[a,b]其中a,b是样式对象;
🌰 例子:
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
 1
data: {
  activeColor: 'red',
  fontSize: 30
}
 1
2
3
4
2
3
4
🌰 例子:
<div v-bind:style="styleObject"></div>
 1
data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}
 1
2
3
4
5
6
2
3
4
5
6
🌰 例子 / 数组:
<div v-bind:style="[baseStyles, overridingStyles]"></div>
 1
对于可能不兼容本浏览器的样式属性,Vue 会自动侦测并添加响应的浏览器引擎前缀。
并且当样式 property 中绑定的是多个兼容浏览器引擎的值的数组例如:
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
 1
这样只会渲染中最后一个被浏览器支持的值。这个例子中如果浏览器支持不带前缀的  flex  ,就只会渲染  display: flex 。
编辑  (opens new window)
  📢 上次更新: 2022/09/02, 10:18:16
