skip to Main Content

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.

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search