1

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?

1
  • actually $style.red: true just adds a class red to your element. And in your css you can do .red { color: red } Commented Sep 10, 2018 at 8:51

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I want to control the variable in js. In this solution, we need to define the class first, but what if the variable is defined by the user? I know we can use css var(), is there any idea in css module?
"The variable is defined by the user." You mean the user can define the class? just bind dynamically the class variable combine it with $style[user_value]
I just mix the class and the variable, sorry. I want to let user control the website's main-color variable which defined in css. I think it can still fulfill by css var(). It's not a question about css module. sorry@@
How does this work with multiple classes? Say .red.container?
you just add array class="[$style.red, $style.container]"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.