【问题标题】:Vue CSS ModulesVue CSS 模块
【发布时间】:2019-02-28 18:27:20
【问题描述】:

我一直在尝试为我们的组件库提出一个解决方案,该解决方案将根据导入的项目以不同的方式呈现样式。在我的研究中,我在 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 模块的目的。

【问题讨论】:

    标签: vuejs2 vue-cli-3 css-modules


    【解决方案1】:

    我通过将 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 文件中的实现。

    【讨论】:

      【解决方案2】:

      有这样一种方法,为了解决这个或类似的问题,如果通过导入,在文件末尾指定模块并处理Computed。然后您可以将 css 类命名为相同,它们不会被覆盖。至少对我来说。

       <template>
        <div id="app" :class="BaseApp.Container">
          <router-view :class="BaseView.Container" />
        </div>
      </template>
      <script>
      import BaseApp from "@/components/Base/Styles/BaseApp.css?module";
      import BaseView from "@/components/Base/Styles/BaseView.css?module";
      export default {
        components: {},
        computed: {
          BaseApp() {
            return BaseApp;
          },
          BaseView() {
            return BaseView;
          },
        },
      };
      </script>
      

      【讨论】:

        猜你喜欢
        • 2019-05-28
        • 2019-07-21
        • 2020-10-02
        • 2019-05-22
        • 2020-12-29
        • 2020-03-23
        • 2020-07-25
        • 2020-09-27
        • 2019-11-02
        相关资源
        最近更新 更多