Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use css module in `setup` function?

Tags:

vue.js

vuejs3

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>
like image 576
yaquawa Avatar asked Apr 28 '26 03:04

yaquawa


2 Answers

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

like image 71
Teena Avatar answered Apr 29 '26 20:04

Teena


vue-loader injects the $style property (via a __cssModules wrapper object) onto the component instance, which can be accessed in <script setup> from getCurrentInstance():

<script setup>
import { getCurrentInstance } from 'vue'
const { $style } = getCurrentInstance().type.__cssModules
console.log('myClass', $style.myClass)
</script>

demo

However, use this solution with caution, as __cssModules is a private/internal property, which can be renamed or removed in the future without warning.

like image 40
tony19 Avatar answered Apr 29 '26 22:04

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!