一、vue2.x 中style使用变量
项目中可能会在style中使用到script中的响应式数据,那么可以采用下面方法:
<template>
<h1>Vue</h1>
</template>
<script>
export default {
data () {
return {
opacity: 0
}
},
mounted () {
setInterval(_ => {
this.opacity >= 1 && (this.opacity = 0)
this.opacity += 0.2
}, 300)
}
}
</script>
<style vars="{ opacity }">
h1 {
color: rgb(65, 184, 131);
opacity: var(--opacity);
}
</style>
如果style标签中使用了scoped,可以使用下面的方式:
<style vars="{ opacity }">
h1 {
color: rgb(65, 184, 131);
opacity: var(--global:opacity);
}
</style>
二、vue3.x 项目中style使用变量
<template>
<h1> shit! </h1>
</template>
<script>
export default {
data () {
return {
color: 'yellow'
}
}
}
</script>
<style>
h1 {
color: v-bind(color)
}
</style>
- 备注: 如果响应式数据是个对象的话,v-bind内的引用需要添加引号
<template>
<h1> shit! </h1>
</template>
<script>
export default {
data () {
return {
font: {
weight: 100
}
}
}
}
</script>
<style>
h1 {
font-weight: v-bind('font.weight')
}
</style>