如何在Vue中使用動態CSS


如何在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>

同樣適用於vue3less的組合

這里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的值,界面也是可以動態發生變化。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM