Solution to using JS defined names as CSS variables in VueJS.
P粉333395496
2023-08-03 20:20:26
<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>
You can create a computed property for a CSS value.
You can also remove :class="$style['colored-text']" and use class="colored-text" directly.
sfc example