vue在css中的动态变量
如下,使用动态css与css中的var()方法即可实现css动态变量
vue
<template>
<div class="box" :style="styleVar">
</div>
</template>
<script>
export default {
props: {
height: {
type: Number,
default: 94,
},
whith: {
type: Number,
default: 200,
},
},
computed: {
styleVar() {
return {
'--box-width': this.whith + 'px',
'--box-height': this.height + 'px'
}
}
},
}
</script>
<style scoped>
.box {
height: var(--box-height);
width: var(--box-width);
background: red;
}
</style>也可以使用ref获取并设置dom,与var()方法配合,实现css动态变量
vue
<template>
<div class="home" ref="UI">
<div class="header">hello world</div>
</div>
</template>
<script>
export default {
data () {
return {
color: 'red'
};
},
mounted(){
this.setUI();
},
methods:{
setUI(){
this.$refs.UI.style.setProperty("--color",this.color); // 给变量赋值
// 如果是自定义组件的话需要用 this.$refs.UI.$el.style.setProperty("--color",this.color) 其中$el代表获取当前dom对象
}
}
}
</script>
<style>
.home{
/* 定义变量 */
--color:'black';
.header{
color: var(--color); //使用变量
}
}
</style>除了var,还可以使用 data- 和 attr()
vue
<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>