Search code examples
cssvuejs3el-plus

Using V-bind to set CSS vars in Vue 3 Composition issue


I apologize ahead of time if the answer is obvious, I'll admit I have never truly understood the bones of CSS vars!

What I am trying to do: Use Vue 3 composition APIs v-bind to override a CSS value of the element plus (don't think the package is relevant but just in case) dynamically using a var.

Here is where I am stumped:

This works:

<template>
    <span class="test">
        TEST
    </span>
    <el-button type="primary">Primary</el-button>
</template>

<script setup lang="ts">
const color = 'green';
</script>

<style>
:root {
    --el-color-primary: green;
}

.test {
    background: v-bind(color);
}
</style>

In the code above both root primary colors are overridden and the .text class uses the color value as expected.

However, if I try:

<style>
:root {
    --el-color-primary: v-bind(color);
}
</style>

It is being "Seen" as not defaulting to its original color (blue). however, It doesn't use the expected value (green) it just uses no color.

Very grateful for anyone who can see what I can't!

EDIT: To reiterate the first block of code I posted works! My question is trying to explore why the second code block --el-color-primary: v-bind(color); does not work.


Solution

  • If you want to change css variables with v-bind() - set this variable to some wrapper in the component.
    If you want to change css variables in :root - use style.setProperty().

    I gave an example of three cases: Vue SFC Playground.