Vue Class 与 Style 的动态绑定

Snipaste_20210318_212010.jpg

Class 对象语法

方式一:

          
  • 1
  • 2
  • 3
  • 4
<div class="static" :class="{ active: isActive, 'text-danger': hasError }" ></div>

对应的数据

          
  • 1
  • 2
  • 3
  • 4
data: { isActive: true, hasError: false }

结果渲染为:

          
  • 1
<div class="static active"></div>

方式二:

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

对应的数据

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
data: { classObject: { active: true, 'text-danger': false } }

结果渲染为:

          
  • 1
<div class="static active"></div>

Class 数组语法

方式一:

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

对应的数据

          
  • 1
  • 2
  • 3
  • 4
data: { activeClass: 'active', errorClass: 'text-danger' }

结果渲染为:

          
  • 1
<div class="active text-danger"></div>

方式二(三元表达式):

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

对应的数据

          
  • 1
  • 2
  • 3
  • 4
  • 5
data: { isActive:true activeClass: 'active', errorClass: 'text-danger' }

结果渲染为:

          
  • 1
<div class="active text-danger"></div>

方式三:

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

对应的数据

          
  • 1
  • 2
  • 3
  • 4
data: { isActive:true errorClass: 'text-danger' }

结果渲染为:

          
  • 1
<div class="active text-danger"></div>

Style 对象语法

方式一:

          
  • 1
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

对应的数据

          
  • 1
  • 2
  • 3
  • 4
data: { activeColor: 'red', fontSize: 30 }

结果渲染为:

          
  • 1
<div style="color: red;font-size: 13px;"></div>

方式二(更清晰):

          
  • 1
<div :style="styleObject"></div>

对应的数据

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
data: { styleObject: { color: 'red', fontSize: '13px' } }

结果渲染为:

          
  • 1
<div style="color: red;font-size: 13px;"></div>

Style 数组语法

方式一:

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

对应的数据

          
  • 1
  • 2
  • 3
  • 4
data: { baseStyles: {color: 'red'}, overridingStyles: {fontSize: '13px'} }

结果渲染为:

          
  • 1
<div style="color: red;font-size: 13px;"></div>

方式二(特殊):

          
  • 1
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>

这样写只会渲染数组中最后一个被浏览器支持的值。在本例中,如果浏览器支持不带浏览器前缀的 flexbox,那么就只会渲染 display: flex。

本文参考Vue官方文档做记录

---end---
(完)
七宗罪
色欲,暴食,贪婪,懒惰,愤怒,嫉妒,傲慢,你有几宗罪?
乌镇一日游
百桥连千巷,曲径皆通幽
重庆4日游
这里做好攻略很重要哦
Python生成一个最简单的rss.xml
feedgen库
Chrome浏览器google翻译无法使用
google翻译无法使用解决方案
小程序获取街道等其他地址信息
运用腾讯位置服务sdk处理更多地图信息
等待你的评论