1. 使用 @import 引入
缺点 无法实现 scoped, 且比价浪费资源
请看以下代码, 我们在一个 scoped 空间里引入外部 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 表示设置为当前页面有效, 但本例中, 代码也使用 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 url;
- @import url list-of-media-queries; (指定媒体查询的条件)
- @import url("fineprint.css") print;
- @import url("bluish.css") projection, tv;
- @import 'custom.css';
- @import url("chrome://communicator/skin/");
- @import "common.css" screen, projection;
- @import url('landscape.css') screen and (orientation:landscape);
2. 使用 src 引入
我们只需把 @import 改成 < style src=""></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
来源: http://www.jianshu.com/p/60a14bb2cfb5