Vue style里面使用@import引入外部css, 作用域是全局的解决方案
問(wèn)題描述
使用@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這句話大家應(yīng)該是見(jiàn)多了, 我也使用scoped, 但是使用@import引入外部樣式表作用域依然是全局的,看了一遍@import的規(guī)則后, 進(jìn)行初步猜測(cè),難道是@import引入外部樣式表錯(cuò)過(guò)了scoped style?
又回想到此前看過(guò)的前端性能優(yōu)化文章里面都有提到,在生產(chǎn)環(huán)境中不要使用@import引入css,因?yàn)樵谡?qǐng)求到的css中含有@import引入css的話,會(huì)發(fā)起請(qǐng)求把@import的css引進(jìn)來(lái),多次請(qǐng)求浪費(fèi)不必要的資源。
@import并不是引入代碼到<style></style>里面,而是發(fā)起新的請(qǐng)求獲得樣式資源,并且沒(méi)有加scoped
<style scoped> @import "../static/css/user.css"; </style>我們只需把@import改成<style src=""></style>引入外部樣式,就可以解決樣式是全局的問(wèn)題
<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技術(shù)文檔 @import
原文地址:https://segmentfault.com/a/1190000012728854
更多專(zhuān)業(yè)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的Vue style里面使用@import引入外部css, 作用域是全局的解决方案的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: vue之computed和watch
- 下一篇: vue路由知识整理