如何在 `setup` 函数中使用 css 模块?
How to use css module in `setup` function?
我可以在 vue3 的设置函数中引用 css 模块中的 class 名称吗?
<script setup>
console.log(this.$style.myClass) // this won't work
</setup>
<style lang="scss" module>
.myClass {
}
</style>
vue-loader
注入 $style
属性(通过 __cssModules
包装器对象)onto the component instance,可以在 <script setup>
中访问getCurrentInstance()
:
<script setup>
import { getCurrentInstance } from 'vue'
const { $style } = getCurrentInstance().type.__cssModules
console.log('myClass', $style.myClass)
</script>
但是,请谨慎使用此解决方案,因为 __cssModules
是一个 private/internal 属性,将来可以在没有警告的情况下重命名或删除。
Vue 文档中有一条警告,禁止使用 getCurrentInstance
(参见:https://twitter.com/romainlanz/status/1486279206149492744?s=20)
Vue 为 css 模块 useCssModule
公开了一个 api 用于此类用例(参见: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>
我在上面使用了相同的示例,两种方法 (Demo) 向您展示了 2 将产生相同的结果,只是 useCssModule
是一个 'lot safer'使用比 getCurrentInstance
我可以在 vue3 的设置函数中引用 css 模块中的 class 名称吗?
<script setup>
console.log(this.$style.myClass) // this won't work
</setup>
<style lang="scss" module>
.myClass {
}
</style>
vue-loader
注入 $style
属性(通过 __cssModules
包装器对象)onto the component instance,可以在 <script setup>
中访问getCurrentInstance()
:
<script setup>
import { getCurrentInstance } from 'vue'
const { $style } = getCurrentInstance().type.__cssModules
console.log('myClass', $style.myClass)
</script>
但是,请谨慎使用此解决方案,因为 __cssModules
是一个 private/internal 属性,将来可以在没有警告的情况下重命名或删除。
Vue 文档中有一条警告,禁止使用 getCurrentInstance
(参见:https://twitter.com/romainlanz/status/1486279206149492744?s=20)
Vue 为 css 模块 useCssModule
公开了一个 api 用于此类用例(参见: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>
我在上面使用了相同的示例,两种方法 (Demo) 向您展示了 2 将产生相同的结果,只是 useCssModule
是一个 'lot safer'使用比 getCurrentInstance