vue中style使用scoped后再使用@import仍为全局作用域

一、问题描述

vue中style使用scoped后再使用@import仍为全局作用域

<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 scoped src=""></style>引入外部样式,就可以解决样式是全局的问题

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped src="../static/css/user.css"></style>
<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>
<style scoped>
.user-content {
	background-color: #3982e5;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值