KayleeGrace
KayleeGrace

Reputation: 94

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.

Upvotes: 2

Views: 11570

Answers (3)

badang
badang

Reputation: 11

try this

<script setup lang="ts">
const color = {test: "green"};
</script>

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

.test {
    background: var(--el-color-primary);
}
</style>

Upvotes: 1

imhvost
imhvost

Reputation: 9959

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.

Upvotes: 4

Mikael Tenshio
Mikael Tenshio

Reputation: 150

if you just want to bind css in the span element by using variable

<span class="test">
        TEST
    </span>

i think you can do this

var color = 'green';
 <span :style="{ color: color }">   TEST</span>

and advice to use composition api

or try this

<el-button class="primary" type="primary">Primary</el-button>


<script>
import {ref} from "vue";
export default {
setup(){

  const color = ref('green');
 
  return{
      color,
}
}
}
</script>
<style scoped>

.primary {

    color: v-bind(color);
}

</style>

Upvotes: -1

Related Questions