1、考虑一个问题, 后端传来一个数据, 比如是某个百分比, 需要在页面做进度展示. 一般的情况都会在 CSS 中设置数据展示, 但是 CSS 中如何获取到后端传来的数据呢?
2、使用自定义属性: data-
通过 v-bind 将后端的数据绑定在自定义 HTML 属性上, 然后通过 CSS 的 attr() 函数获取该属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <template>
<div>
<div class= "box"
:data-content= "obj.desc"
:data-percent= "obj.percent" ></div>
</div>
</template>
<script>
export default {
data() {
return {
obj: {
percent: '30%' ,
desc: '哈哈哈哈哈哈'
}
}
},
}
</script>
<style>
.box {
width: 400px;
height: 200px;
border: 1px solid salmon;
position: relative;
}
.box::before, .box::after {
position: absolute;
top: 0; bottom: 0;
}
.box::before {
content: attr(data-content);
left: 0;
right: calc(100% - attr(data-percent));
background-color: deepskyblue;
}
.box::after {
content: attr(data-content);
right: 0;
left: attr(data-percent);
background-color: deeppink;
}
</style>
|
最后页面展示

?计算 right 部分失效了, 原因是 attr() 函数不能在 calc() 中使用! 怎么办呢?
3、自定义 CSS 变量
通过在 HTML 的 style 属性以 v-bind 的形式绑定定义的 CSS 变量, 继而在 CSS 中使用该变量达到效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <template>
<div>
<div class= "box"
:style= "{'--percent': obj.percent}"
:data-content= "obj.desc"
:data-percent= "obj.percent" ></div>
</div>
</template>
<style>
.box {
width: 400px;
height: 200px;
border: 1px solid salmon;
position: relative;
}
.box::before, .box::after {
position: absolute;
top: 0; bottom: 0;
}
.box::before {
content: attr(data-content);
left: 0;
/* right: calc(100% - attr(data-percent)); */
right: calc(100% - var (--percent));
background-color: deepskyblue;
}
.box::after {
content: attr(data-content);
right: 0;
/* left: attr(data-percent); */
left: var (--percent);
background-color: deeppink;
}
</style>
|
上面的代码省略了 <script> 标签部分, 因为这部分没有改动

