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>
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With