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>


  • 2017-02-13 17:50:05

    cURL error 60: SSL certificate problem: unable to get local issuer certificate

    Drupal 8 version uses Guzzle Http Client internally, but under the hood it may use cURL or PHP internals. If you installed PHP cURL on your PHP server it typically uses cURL and you may see an exception with error Peer certificate cannot be authenticated with known CA certificates or error code CURLE_SSL_CACERT (60).

  • 2017-02-16 08:09:01

    HTML中PRE和p的区别

    pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。 <pre> 标签的一个常见应用就是用来表示计算机的源代码。

  • 2017-02-16 15:14:14

    动态加载js和css

    开发过程中经常需要动态加载js和css,今天特意总结了一下常用的方法。

  • 2017-02-17 17:11:24

    mysql插入数据后返回自增ID的方法c

    产生的ID 每次连接后保存在服务器中。这意味着函数向一个给定客户端返回的值是该客户端产生对影响AUTO_INCREMENT列的最新语句第一个 AUTO_INCREMENT值的。这个值不能被其它客户端影响,即使它们产生它们自己的 AUTO_INCREMENT值。这个行为保证了你能够找回自己的 ID 而不用担心其它客户端的活动,而且不需要加锁或处理