在 Vuejs 中拥有全局 css 的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39438094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 12:07:40  来源:igfitidea点击:

Best way to have global css in Vuejs

cssimportvue.js

提问by Jordy

What is the best way to have a global css file in Vuejs for all components? (Default css like bg color, button styling, etc)

在 Vuejs 中为所有组件创建全局 css 文件的最佳方法是什么?(默认 css,如 bg 颜色、按钮样式等)

  • import a css file in the index.html
  • do @import in main component
  • put all the css in the main component (but that would be a huge file)
  • 在 index.html 中导入一个 css 文件
  • 在主要组件中做@import
  • 将所有 css 放在主要组件中(但这将是一个巨大的文件)

回答by highFlyingSmurfs

Import css in your index.html, but if you're using webpack you can just import your stylesheets in your main js config and all your components will get the css.

在 index.html 中导入 css,但如果您使用 webpack,则只需在主 js 配置中导入样式表,所有组件都会获得 css。

As comments below suggested if using webpack adding this to main.js works:

如果使用 webpack 将其添加到 main.js 中,则建议如下评论:

import './assets/css/main.css';

回答by Coder Absolute

I found the best way is to create a new file in the assets folder, I created as global.cssbut you can name anything of your choice. Then, import this file global.cssfile in the main.js.

我发现最好的方法是在资产文件夹中创建一个新文件,我创建了 asglobal.css但您可以命名任何您选择的文件。然后,将这个文件global.css文件导入到main.js.

Note: Using this approach you can also create multiple files if you think the global.css is getting really large then simply import all those files in the main.js.

注意:如果您认为 global.css 变得非常大,则使用这种方法还可以创建多个文件,然后只需将所有这些文件导入 main.js。

@\assets\global.css

@\assets\global.css

/* move the buttons to the right */
.buttons-align-right {
  justify-content: flex-end;
}


main.js

主文件



import Vue from 'vue'
import App from './App.vue'
import router from './routes'

Vue.config.productionTip = false

// Importing the global css file
import "@/assets/global.css"

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

回答by PeeJee

You can also do something like this: https://css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/

你也可以这样做:https: //css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/

My folders are mostly structured like this:

我的文件夹的结构主要是这样的:

 - src
   - assets
     - _global.scss
     - _colors.scss
     - _fonts.scss
     - _paragraphs
     - index.scss // <-- import all other scss files.

This also works with normal css.

这也适用于普通的 css。

回答by c24b

In App.vue you can add a styleproperty to declare you CSS file:

在 App.vue 中,您可以添加一个style属性来声明您的 CSS 文件:

<style>
  @import './assets/css/global.css';
</style>