摘要

本文介绍了如何在 Vue 项目中通过纯 CSS 与 Vue 的动态绑定实现数据驱动的样式变化:

使用 :vote-badge="blog.voteCount"voteCount 绑定到元素自定义属性,配合伪元素 content: attr(vote-badge) 实现点赞数的动态展示;

利用 :style="{'--item-count': item.count}" 动态设置 CSS 变量 --item-count,并在样式表中通过 height: calc(var(--item-count) * 40px) 根据数据动态计算元素高度。

<!-->Yo, this is for a Vue project<-->
<div class="test-div" :vote-badge="`${blog.voteCount}`"></div>

<div
  class="test-div1"
  :style="{'--item-count':item.count}"
  :vote-badge="`${blog.voteCount}`"></div>
.test-div:after {
  content: attr(vote-badge);
}

.test-div1 {
  height: calc(var(--item-count) * 40px);
}