Vue单页面应用中某组件设置了scoped的style标签为什么对import的css文件无效

1.
<style scoped>
    @import '../../assets/css/home.css';  
</style>
/*这样写的话import的css文件会被编译为全局样式,最后直接通过style标签加在页面中*/

2.
<style src="../../assets/css/home.css" scoped>
</style>
/*这样写的css文件中的样式只能在本组件中使用,而不会影响其他组件*/

后来,我找了一下关于css-loader和style-loader的资料,粗略了解它们的工作原理,有一种说法是css-loader对import的文件会当做外部资源,那么我能理解为它是把import的css文件单独提取出来,并没有把其中的样式放在<style scoped>中解析,而是最后把<style>中计算结果和import的css文件混合后,交由style-loader最后解析为style标签加载在页面里吗?

在<style>中import的css文件是怎么处理的,和<style>其他裸样式的加载顺序有什么不一样吗?(我在一个地方看到有一个说法是import的css文件会等到dom树下载完才会被加载?)import的原理是什么?

阅读 7.1k
3 个回答

尝试了一下,你所说的第一种方式

<style scoped>
    @import 'xxx';
 </style>

所编译的出来的CSS还是局部的样式,以下例子

test.vue

<template>
  <div id="test">
    <h1>this is a test</h1>
  </div>
</template>

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

test.css

h1 {
  color: #39baa7;
  font: bold 24px/150% Microsoft Yahei;
}

编译结果
11124951.jpg

下面验证他到底是不是局部,给test.vue添加一个子路由testchild,如下
test.vue

<template>
  <div id="test">
    <h1>this is a test</h1>
    <router-link to="/test/child">
      <span>vuejs</span>
    </router-link>
    <router-view></router-view>
  </div>
</template>

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

testchild.vue

<template>
  <div id="testchild">
    <h1>this is a test child</h1>
  </div>
</template>

<style>

</style>

结果
3704364.jpg

可见,父路由的style并不会影响子路由的style。
综上,在style scoped所@import的css文件编译出来的还是拥有自己的作用域的,不会污染其他vue组件的样式。
相关资料:
less @import can't work fine with scoped #235

我也不是很明白你的疑问,推荐一个vue-loader的文档吧,看能不能解决你的困惑。

推荐问题