Vue 項目CSS組織

1.頁面樣式書寫方法

參考文章


2.import 和@import 導入樣式

import JS中引入css

import "./common/uni.css"

注意:這種寫法適用於css文件存在於項目中,不適用於通過url訪問的方式引入

@import必須寫在style中

<style>
    @import "/common/uni.css";
</style>

用於從其他樣式表導入樣式規則。這些規則必須先於所有其他類型的規則,@charset 規則除外。@import應寫在樣式表的開頭,否則無法正確導入外部文件。


3.全局樣式引入

(1)在index.html中引入
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>hello</title>
 <link rel="stylesheet" href="./static/css/global.css"> /*引入公共樣式*/
 </head>
 <body>
  <div id="app"></div>
  <!-- built files will be auto injected -->
 </body>
</html>
(2)在入口js文件main.js中引入
import Vue from 'vue'
import App from './App' // 引入App這個組件
import router from './router' /* 引入路由配置 */
import axios from 'axios'
import '../static/css/global.css' /*引入公共樣式*/
(3)在app.vue中引入,但是這樣引入有一個問題,就是在 index.html的head上會多出一個空的<style></style>
<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
  @import './../static/css/global.css'; /*引入公共樣式*/
</style>

4.作用域的 CSS

在vue單文件組件中,爲了防止全局同css類名名樣式的污染,vue-loade對單文件組件 <style> 標籤增加了scoped屬性的處理。原理就是在html標籤上添加data-v-xxxxxxxx屬性,然後在css類名後添加屬性選擇器,即利用css類選擇 + 屬性選擇器實現樣式局部化

<style>
  /* 全局樣式 */
</style>
<style scoped>
  /* 本地樣式 */
</style>

因爲權重的問題,如果是在子組件使用了scoped,那麼在父組件中是不能直接修改子組件的樣式的,需要在父組件中使用vue的深度作用選擇器。
但是<style scoped>裏面使用@import 引入css是全局的

<style scoped>
    @import '../../assets/css/home.css';  
</style>

css-loader對import的文件會當做外部資源,那麼我能理解爲它是把import的css文件單獨提取出來,並沒有把其中的樣式放在<style scoped>中解析,而是最後把<style>中計算結果和import的css文件混合後,交由style-loader最後解析爲style標籤加載在頁面裏。

<style src="../../assets/css/home.css" scoped>
</style>

這樣是css文件中的樣式只能在本組件中使用,而不會影響其他組件


5.使用sass

在 webpack 中,所有的預處理器需要匹配對應的 loader。vue-loader 允許你使用其它 webpack loader 處理 Vue 組件的某一部分。它會根據 lang 屬性自動推斷出要使用的 loader。
這是全局

<style lang="scss">
@import "./styles/_colors.scss"; //全局
.m-header {
  position: relative;
  height: 44px;
  width: 100%;
  text-align: center;
  background: $color-theme;
}
</style>

這是局部

<style lang="scss" scoped>
@import "~common/scss/variable.scss"; //局部
.m-header {
  position: relative;
  height: 44px;
  width: 100%;
  text-align: center;
  background: $color-theme;
}

6.vue-loader

vue-loader
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章