鍍金池/ 問答/HTML5  HTML/ Vue單頁面應(yīng)用中某組件設(shè)置了scoped的style標(biāo)簽為什么對import的

Vue單頁面應(yīng)用中某組件設(shè)置了scoped的style標(biāo)簽為什么對import的css文件無效

1.
<style scoped>
    @import '../../assets/css/home.css';  
</style>
/*這樣寫的話import的css文件會被編譯為全局樣式,最后直接通過style標(biāo)簽加在頁面中*/

2.
<style src="../../assets/css/home.css" scoped>
</style>
/*這樣寫的css文件中的樣式只能在本組件中使用,而不會影響其他組件*/

后來,我找了一下關(guān)于css-loader和style-loader的資料,粗略了解它們的工作原理,有一種說法是css-loader對import的文件會當(dāng)做外部資源,那么我能理解為它是把import的css文件單獨(dú)提取出來,并沒有把其中的樣式放在<style scoped>中解析,而是最后把<style>中計算結(jié)果和import的css文件混合后,交由style-loader最后解析為style標(biāo)簽加載在頁面里嗎?

在<style>中import的css文件是怎么處理的,和<style>其他裸樣式的加載順序有什么不一樣嗎?(我在一個地方看到有一個說法是import的css文件會等到dom樹下載完才會被加載?)import的原理是什么?

回答
編輯回答
夕顏

嘗試了一下,你所說的第一種方式

<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;
}

編譯結(jié)果
11124951.jpg

下面驗(yàn)證他到底是不是局部,給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>

結(jié)果
3704364.jpg

可見,父路由的style并不會影響子路由的style。
綜上,在style scoped所@import的css文件編譯出來的還是擁有自己的作用域的,不會污染其他vue組件的樣式。
相關(guān)資料:
less @import can't work fine with scoped #235

2017年12月9日 07:05
編輯回答
歆久

我也不是很明白你的疑問,推薦一個vue-loader的文檔吧,看能不能解決你的困惑。

2017年12月22日 00:15