'How to use css module in `setup` function?

Can I refer class name from css module in the setup function of vue3?

<script setup>

console.log(this.$style.myClass) // this won't work

</setup>

<style lang="scss" module>
.myClass {

}
</style>


Solution 1:[1]

There is a warning in the Vue docs against the use of getCurrentInstance (see: https://twitter.com/romainlanz/status/1486279206149492744?s=20)

Vue exposes an api for css modules useCssModule for such use cases (see: https://vuejs.org/api/sfc-css-features.html#usage-with-composition-api)

<script setup>
import { useCssModule } from 'vue'

const $style = useCssModule()
console.log($style.myClass) // This Works ?

</setup>

<style lang="scss" module>
.myClass {}
</style>

I used the same example above, with both approaches, (Demo) to show you that the 2 will produce the same thing, just that useCssModule is a 'lot safer' to use than getCurrentInstance

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Teena