Vue style裏面使用@import引入外部css, 做用域是全局的解決方案

問題描述

使用@import引入外部css,做用域倒是全局的css

<template>

</template>

<script>
    export default {
        name: "user"
    };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
@import "../static/css/user.css";
.user-content{
  background-color: #3982e5;
}
</style>
Add "scoped" attribute to limit CSS to this component only

這句話你們應該是見多了, 我也使用scoped, 可是使用@import引入外部樣式表做用域依然是全局的,看了一遍@import的規則後, 進行初步猜想,難道是@import引入外部樣式表錯過了scoped style?前端

又回想到此前看過的前端性能優化文章裏面都有提到,在生產環境中不要使用@import引入css,由於在請求到的css中含有@import引入css的話,會發起請求把@import的css引進來,屢次請求浪費沒必要要的資源。vue

@import並非引入代碼到<style></style>裏面,而是發起新的請求得到樣式資源,而且沒有加scoped性能優化

<style scoped>
@import "../static/css/user.css";
</style>

咱們只需把@import改爲<style src=""></style>引入外部樣式,就能夠解決樣式是全局的問題前端性能

<style scoped src="../static/css/user.css">
<style scoped>
.user-content{
  background-color: #3982e5;
}
</style>

總體代碼以下:性能

<template>

</template>

<script>
    export default {
        name: "user"
    };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped src="../static/css/user.css">
<style scoped>
.user-content{
  background-color: #3982e5;
}
</style>

參考連接

MDN Web技術文檔 @import優化

相關文章
相關標籤/搜索