vuejs 仅导入一次 css 文件



我有一个有很多页面的大型网站,对于 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 文件?

在我看来,你应该将每个页面拆分为一个单独的 Vue 组件,然后在根组件中具有通用样式,并在组件本身中声明每个页面的特定规则(设置了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>

最新更新