首页 > 解决方案 > Vue CSS 模块

问题描述

我一直在尝试为我们的组件库提出一个解决方案,该解决方案将根据导入的项目以不同的方式呈现样式。在我的研究中,我在 CSS 模块中找到了一个可能的解决方案。我目前面临的问题是,当我使用命名模块时,它们会编译为同一个 css 类,因此两个不同命名模块中的样式会相互覆盖。Vue 网站上的文档非常少,所以我不确定我当前是否正确地实现了我的代码。有人可以让我知道我是否遗漏了某些东西,或者他们以前是否遇到过类似的问题?

<template>
  <button :class="a.button" type="button" v-on="$listeners">
    <slot/>
  </button>
</template>

<script>
export default {
  console.log(this.a, this.b)
}
</script>

<style module="a">
.button {
  background-color: red;
}
/* identifiers injected as a */
</style>

<style module="b">
.button {
  background-color: blue;
}
/* identifiers injected as b */
</style>

在我console.log(this.a, this.b)的控制台中,两个渲染的类名都返回相同{button: "index_button_2JdpP"} {button: "index_button_2JdpP"},因此很明显我的代码存在问题,或者我误解了命名 CSS 模块的目的。

标签: vuejs2vue-cli-3css-modules

解决方案


我通过将 CSS 文件导入脚本并使用计算属性设置样式来找到解决方法。

<template>
  <button type="button" :class="styles.button" v-on="$listeners">
    <slot/>
  </button>
</template>

<script>
import remax from './remax.scss'
import crm from './crm.scss'

export default {
  computed: {
    styles() {
      return remax
    },
  }
}
</script>

<style modules lang="scss"></style>

不幸的是,以这种方式做事已经在我的项目中引入了一些样式,但这可能是由于我在 scss 文件中的实现。


推荐阅读