Search code examples
javascriptvue.jscss-modulescss-variables

Can I modify a CSS variable from VueJS?


CSS Modules let us use the variable in both CSS and JS.

// use in temaplate
...
...<p :class="{ [$style.red]: isRed }">Am I red?</p>

// use in js 
...
...
<script>
export default {
    created () {
        console.log(this.$style.red)
        // -> "red_1VyoJ-uZ"
        // an identifier generated based on filename and className.
    }
}
</script>

/// use in css preprocessor
...
...
<style lang="stylus" module>
.red {
  color: red;
}
</style>

We can get the variable no matter in template, JS or CSS. But if we have some feature like: click and change all website's "main-color" which define in CSS.

Can we change the variable in JS?


Solution

  • A CSS Module is a CSS file in which all class names and animation names are scoped locally by default

    So use them when you want to be sure a component style will not overridden.

    I am not sure what you asking for so I am assuming you want to dynamically change the css module class.

    Template:

    <template>
      <div>
       <div :class="[module]">I am a div</div>
       <button @click="make_blue_class">Make it blue</button>
       <button @click="make_red_class">Make it red</button>
      </div>
    </template>
    

    Script:

      data: () => ({
        module_class: 'red'
      }),
    
      computed: {
        module: {
          get() {
            return this.$style[this.module_class]
          },
          set(new_class) {
            this.module_class = new_class
          }
        }
      },
      methods: {
        make_blue_class() {
          this.module_class = 'blue'
        },
        make_red_class() {
          this.module_class = 'red'
        }
      }
    

    Style:

      .red {
        background: red;
      }
      .blue {
        background: blue;
      }
    

    See it in action here