使用CSS变量
2.X
Vue2 中,我们通常使用计算属性反映 data 中的 变量到 css 中,使用计算属性来绑定
<template>
<div :style="styleObj">
<p class="text">测试文本</p>
</div>
</template>
<script>
export default {
data() {
return {
color: "red"
};
},
computed: {
styleObj() {
return {
"--color": this.color
};
}
}
};
</script>
<style lang="scss" scoped>
.text {
color: var(--color);
}
</style>
3.X
<template>
<div>
<p class="text">测试文本</p>
</div>
</template>
<script>
export default {
data() {
return {
color: "red"
};
}
};
</script>
<style scoped vars="{ color }">
.text {
color: var(--color);
}
</style>
<template>
<div :style="{ backgroundColor: customColor }">
<!-- Your content here -->
</div>
</template>
<script setup>
import { ref } from 'vue';
const customColor = ref('#007bff');
</script>
<style>
:root {
--primary-color: {{ customColor }};
}
</style>