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