【问题标题】:vuejs Importing css file only oncevuejs只导入一次css文件
【发布时间】:2018-02-16 22:05:01
【问题描述】:

我有一个包含很多页面的大型网站,对于 4-6 个页面,我需要一个特定的 css 代码。我不想将此 css 代码添加到全局文件中,而是希望每当浏览页面中的任何人时,只加载一次相关的特定文件。我试过这样的事情

.....
//page 45
<style>
  @import '../../styles/boxes.css'
</style>
......
.....
//page 46
<style>
  @import '../../styles/boxes.css'
</style>
......
.....
//page 47
<style>
  @import '../../styles/boxes.css'
</style>
......
....

这种方法的问题是现在我多次出现相同的 css 代码。 .vue 文件中是否有任何方法可以仅在尚未导入的情况下导入 box.css 文件?

【问题讨论】:

    标签: webpack vuejs2 webpack-style-loader


    【解决方案1】:

    在我看来,您应该将每个页面拆分为单独的 Vue component,然后在根组件中使用通用样式,并在组件本身中声明每个页面的特定规则(使用 scoped 属性集)。

    例如:

    在你的根组件中:

    // App.vue
    <template>
      <div id="app">
        <page1></page1>
        <page2></page2>
        ...
      </div>
    </template>
    
    <script>
    import Page1 from './components/Page1'
    import Page2 from './components/Page2'
    ...
    
    export default {
      name: 'app',
      components: {
        Page1,
        Page2,
        ...
      }
    }
    </script>
    
    <style>
      // these rules are available globally
      @import './assets/boxes.css'
    </style>
    

    在具有特定样式规则的页面中:

    // Page1.vue
    <template>
      <div>
        <h1>Page 1</h1>
      </div>
    </template>
    
    <style scoped>
      // with the `scoped` attribute, these rules will only apply to this component
      h1 {
        color: red;
      }
    </style>
    

    【讨论】:

      猜你喜欢
      • 2019-08-29
      • 2019-04-27
      • 2017-09-20
      • 2018-02-20
      • 1970-01-01
      • 2017-06-09
      • 2015-09-16
      • 2020-05-31
      • 1970-01-01
      相关资源
      最近更新 更多