[英]Proper way of adding CSS file in Vue.js Application
在 Vue.js 應用程序中添加外部 CSS 文件的正確方法是什么?
我找到了幾種在 Vue.js 應用程序中添加 CSS 文件的方法。
有人建議使用這個。 <link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">
。
有人建議這個
<style lang="scss">
@import 'src/assets/css/mycss_lib.css';
</style>
有人建議這個
require('./assets/layout3/css/layout.min.css')
有人建議在webpack.config.js
使用以下代碼。
{
test: /\.(css|less)$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
}
有人建議使用這個
<style src="../node_modules/vue-multiselect/dist/vue-multiselect.min.css"></style>
使用所有這些方式的優缺點是什么?
我想以某種方式使用,以便所有 CSS 文件在部署時成為一個文件。 這樣我的應用程序加載速度更快。
npm install sass-loader --save-dev
在src/assets
目錄下創建新的css
目錄
在新的css
目錄下創建一個styles.scss
文件
將以下代碼行添加到您的main.js
文件中
import '../src/assets/css/styles.css';
在styles.scss
文件中,您可以導入多個css 文件。
@import '~bootstrap/scss/bootstrap.min.css';
@import './common.css';
您還可以在同一個文件中編寫像這樣的常規 CSS 屬性
body {
background: gray;
}
div {
font-weight: bold;
}
npm run serve
在 Vue.js 中對我來說最好的方法(!)是在我的主 index.html 中使用鏈接標簽包含全局頁面樣式。 這樣它們就可以從任何地方訪問,並在第一次打開頁面時加載。 像這樣: index.html:
<link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">
我的組件的樣式規則使用以下內容內聯在 .vue 文件中: mycomponent.vue:
<style scoped>
...
</style>
編輯:
如果您不想使用 .vue 文件並使用 .js 文件,則不能將 css 限定在組件內。 如果是這種情況,我總是將它們命名為與組件相同的名稱,並將其包含在 index.html 中的鏈接標簽中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.