如何在Vue中使用動態CSS
開發過程中,有需要通過script去動態修改css樣式中某些屬性值,比如 主題切換。
v-bind
<style>標記支持使用v-bind 將CSS值鏈接到組件狀態
<template>
<div class="text">hello</div>
</template>
<script>
export default {
data() {
return {
color: 'red'
}
}
}
</script>
<style>
.text {
color: v-bind(color);
}
</style>
同樣適用於vue3 何 less的組合
這里v-bind() 中必須使用引號。
<template>
<div class="text">hello</div>
</template>
<script>
import { defineComponent, reactive } from 'vue'
export default defineComponent({
setup() {
const theme = reactive({
color: 'red'
})
return {
theme
}
}
})
</script>
<style lang="less" scoped>
.text {
color: v-bind('theme.color');
}
</style>
還可以動態修改theme中color的值,界面也是可以動態發生變化。
