静态绑定内联样式
v-bind:style
的对象语法十分直观,CSS属性名可以用 驼峰式 (camelCase) 或 短横线分隔 (kebab-case,记得用引号括起来) 来命名:
- 对象
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data: {
activeColor: 'red',
fontSize: 30
}
直接绑定到一个样式对象通常更好,这会让模板更清晰:
<div v-bind:style="styleObject"></div>
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
三元判断的对象
<div :style="{color:(index == 0 ? conFontColor : '#000')}"></div>
- 数组
三元多属性
:style="[{height:(warnData.length > 0?'calc(100% - 54px - 42px)':'calc(100% - 54px)')},{color:'#fff'}]"
动态绑定内联样式
本文以 CSS Grid 网格布局教程 为例,解释如何用传参的形式,动态绑定内联样式
- 使用计算属性computed
对象语法常常结合返回对象的计算属性使用。
计算属性系统自己会执行前一层函数,所以需要以函数的形式返回样式,直接返回对象需要加括号,不加括号就认为是箭头函数的大括号了。
<div class="container">
<div
v-for="(item, index) in items"
:key="index"
class="item.name"
:style="itemObject(item)"
>
{{ item.name }}
</div>
</div>
data() {
return {
items: [
{
'name': 'PWR_1',
'background': '#e5e4e9',
'columnStart': 1,
'columnEnd': 2,
'rowStart': 1,
'rowEnd': 2
},
{
'name': 'FAN_1',
'background': '#e5e4e9',
'columnStart': 2,
'columnEnd': 3,
'rowStart': 1,
'rowEnd': 2
},
{
'name': 'FAN_2',
'background': '#e5e4e9',
'columnStart': 3,
'columnEnd': 4,
'rowStart': 1,
'rowEnd': 2
}
]
}
},
computed: {
itemObject(item) {
return (item) => ({
backgroundColor: item.background,
gridColumnStart: item.columnStart,
gridColumnEnd: item.columnEnd,
gridRowStart: item.rowStart,
gridRowEnd: item.rowEnd
})
}
}
.container {
display: grid;
grid-template-columns: repeat(4, 25%);
grid-template-rows: repeat(2, 30px);
}
.item {
font-size: 12px;
text-align: center;
border: 1px solid white;
display: flex;
justify-content: center;
align-items: center;
}