vue中css/scss使用(上)

451 阅读2分钟

内容太多分为上下两章,本章主要是css的使用

内部样式

global

正常情况下组件内部的css会直接放到一个 <style> 标签中

需要注意的是此时样式为全局样式,如果其他组件有相同的css选择器则会互相影响样式

图片路径: /src/assets/logo.png

/src/views/AboutView.vue

 <template>
   <div class="about">
     <h1>This is an about page</h1>
     <div class="box"></div>
   </div>
 </template>
 ​
 <style>
 .about {
   background-color: pink;
 }
 .box {
   width: 200px;
   height: 200px;
   background-image: url("../assets/logo.png");
 }
 </style>

image-20220628174407052.png

scoped

如果在组件中的 <style> 标签中加上scoped属性则会自动在组件上添加一个唯一的自定义属性,格式为:data-v-xxxxxxxxxx为随机生成

编译后的css选择器后面会自动加上属性选择器 [data-v-xxxxx] ,这样就可以为css指定作用域

/src/views/AboutView.vue

 <template>
   <div class="about">
     <h1>This is an about page</h1>
     <div class="box"></div>
   </div>
 </template>
 ​
 <style scoped>
 .about {
   background-color: pink;
 }
 .box {
   width: 200px;
   height: 200px;
   background-image: url("../assets/logo.png");
 }
 </style>

image-20220628174141209.png

外部样式

@import

外部样式可以通过 @import引入, @import@import url() 均可使用

需要注意的是使用文件引入方式,css中使用图片路径是以css文件所在目录为起点

图片路径: /src/assets/logo.png

/src/assets/css/about.css

 .about {
     background-color: pink;
 }
 .box {
     width: 200px;
     height: 200px;
     background-image: url("../logo.png");
 }

/src/views/AboutView.vue

 <template>
   <div class="about">
     <h1>This is an about page</h1>
     <div class="box"></div>
   </div>
 </template>
 ​
 <style>
 /* 以下三种写法均可 */
 @import "../assets/css/about.css";
 /* @import url("../assets/css/about.css"); */
 /* @import url(../assets/css/about.css); */
 </style>

scoped

<style> 加上scoped属性后使用 @import会发现编译后组件上添加了自定义属性data-v-xxxxx,但是css选择器并没有加属性选择器 [data-v-xxxxx]

这是由于 @import引入的文件会当做外部资源,没有把其中的样式放在当前组件 <style> 中,而是单独解析为一个 <style> 加载到页面里

/src/views/AboutView.vue

 <template>
   <div class="about">
     <h1>This is an about page</h1>
     <div class="box"></div>
   </div>
 </template>
 ​
 <style scoped>
 @import "../assets/css/about.css";
 </style>

image-20220628193155667.png

解决方案:

<style> 中使用src引入外部样式即可

 <template>
   <div class="about">
     <h1>This is an about page</h1>
     <div class="box"></div>
   </div>
 </template>
 ​
 <style src="../assets/css/about.css" scoped>
 </style>

关于public

如果图片放在public中想通过css引用,在 @vue/cli5@vue/cli4.5中写法略有不同

图片路径: /public/logo.png

@vue/cli5

/src/views/AboutView.vue

 <template>
   <div class="about">
     <h1>This is an about page</h1>
     <div class="box"></div>
   </div>
 </template>
 ​
 <style scoped>
 .about {
   background-color: pink;
 }
 ​
 .box {
   width: 200px;
   height: 200px;
   background-image: url("/public/logo.png");
 }
 </style>

@vue/cli4.5

/src/views/About.vue

 <template>
   <div class="about">
     <h1>This is an about page</h1>
     <div class="box"></div>
   </div>
 </template>
 ​
 <style scoped>
 .about {
   background-color: pink;
 }
 ​
 .box {
   width: 200px;
   height: 200px;
   background-image: url("/logo.png");
 }
 </style>