vue 静态/动态绑定style的几种方式【Vue】

静态绑定内联样式

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;
}
  • 14
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值