如何在`setup`函数中使用css模块?

yaq*_*awa 1 vue.js vuejs3

我可以在vue3的setup函数中引用css模块中的类名吗?

<script setup>

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

</setup>

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

}
</style>
Run Code Online (Sandbox Code Playgroud)

小智 11

Vue 文档中有一个反对使用的警告getCurrentInstance(请参阅:https://twitter.com/romainlanz/status/1486279206149492744 ?s=20 )

\n

Vue 为此类用例公开了 css 模块的 api useCssModule(请参阅: https: //vuejs.org/api/sfc-css-features.html#usage-with-composition-api

\n
<script setup>\nimport { useCssModule } from \'vue\'\n\nconst $style = useCssModule()\nconsole.log($style.myClass) // This Works \xe2\x9c\x85\n\n</setup>\n\n<style lang="scss" module>\n.myClass {}\n</style>\n
Run Code Online (Sandbox Code Playgroud)\n

我使用上面的相同示例,使用两种方法(演示)来向您展示这两种方法将产生相同的结果,只是useCssModule使用起来比使用“安全得多”getCurrentInstance

\n