不知道大家有没有一种要是class类中可以使用js中的变量就好了的想法。
其实很简单,首先在html或者js中定义css变量,然后通过行内注入的方式将变量和css关联起来,最后通过CSS var()函数读取注入的变量即可。
vue代码如下:
<template>
<div class="hello">
<p class="useVar" :style="newStyle">hello world</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
fontSize:{
type: Number,
default: 30
}
},
data(){
return {
color: 'red'
}
},
computed: {
newStyle(){
return {
'--useColor': this.color,
'--useFontSize': this.fontSize+'px'
}
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.useVar {
color: var(--useColor);
font-size: var(--useFontSize);
}
</style>