Solution to using JS defined names as CSS variables in VueJS.
P粉333395496
P粉333395496 2023-08-03 20:20:26
0
1
642
<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粉333395496
P粉333395496

reply all(1)
P粉302160436

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template