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

2020-05-06 18:46:06

错误的做法

<style>

@import "../static/css/user.css";

</style>

正确的做法


我们只需把@import改成<style src=""></style>引入外部样式,就可以解决样式是全局的问题

参考地址 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>


  • 2020-02-06 13:32:10

    android.os.NetworkOnMainThreadException

    在Android 4.0以上,网络连接不能放在主线程上,不然就会报错android.os.NetworkOnMainThreadException。但是4.0下版本可以不会报错。

  • 2020-02-07 23:46:44

    You must call removeView() on the child's parent first解决办法

    出现这样的情况最多是发生在recyclerView中,holder复用的过程中,多次添加view,第一次添加的时候view有了父类了,可能就是复用引起的。 我是发生在给recyclerView添加广告view的时候发生的。

  • 2020-02-11 17:43:35

    基于VCamera,仿微信录制短视频

    vcamera.so这个确实挺好用,可定制性也挺高,但是确定也不小,需要引入的这个so包,10M啊。对于安装包苛刻的用户,这是致命啊。 我现在是抛弃他了。但是在这里还是记录一下用法吧。防止以后再用他。

  • 2020-02-13 13:37:53

    mysql随机排序

    首页热门栏目需要随机显示几条信息

  • 2020-02-14 20:08:17

    Android-应用被作为第三方浏览器打开

    微信里的文章页面,可以选择“在浏览器打开”。现在很多应用都内嵌了WebView,那是否可以使自己的应用作为第三方浏览器打开此文章呢?