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


問題描述

使用@import引入外部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引進來,多次請求浪費不必要的資源。

@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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM