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