search

Home  >  Q&A  >  body text

Solution to using JS defined names as CSS variables in VueJS.

<p>I'm using Vuetify which creates CSS variables for each theme color (like --v-theme-primary). I want to be able to set the color to --v-theme-{something} in CSS, and have the value of {something} come from JS. For example: </p> <pre class="brush:js;toolbar:false;"><template> <div :class="$style['colored-text']">Asd</div> </template> <script lang="ts" setup> const color = ref("primary") </script> <style lang="scss" module> .colored-text { background-color: var(--v-theme-[[v-bind(color)]]); } </style> </pre> <p> [[v-bind(color)]] is invalid syntax, I just brought it up for demonstration. I want to be able to put the color name or something from the color reference in there so that I can use var(--v-theme-{color}) in CSS where the color comes from JS. In the example, it would become var(--v-theme-primary). <br /><br />Do you have any ideas? Is this approach feasible? </p><p><br /></p>
P粉333395496P粉333395496479 days ago625

reply all(1)I'll reply

  • P粉302160436

    P粉3021604362023-08-04 00:35:30

    You can create a computed property for a CSS value.

    You can also remove :class="$style['colored-text']" and use class="colored-text" directly.

    <template>
      <div class="colored-text">Asd</div>
    </template>
    
    <script lang="ts" setup>
      import { ref, computed } from 'vue'
      const color = ref("primary")
      const bgColor = computed(()=>`var(--v-theme-${color}`)
    </script>
    
    <style>
    .colored-text {
      background-color: v-bind(bgColor);
    }
    </style>
    

    sfc example

    reply
    0
  • Cancelreply