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>
CodePudding user response:
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>
However, use this solution with caution, as __cssModules
is a private/internal property, which can be renamed or removed in the future without warning.