Dom节点定义数据

摘要

本文介绍了如何在 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) 根据数据动态计算元素高度。

1
2
3
4
5
6
7
<!-->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>
1
2
3
4
5
6
7
.test-div:after {
content: attr(vote-badge);
}

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