小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
代码是写给人看的, 顺便给机器运行 !
前言
上面的两篇文章分别介绍了 Vue
代码中的 script
和 Vue
中的 template
两个部分的代码规范,本文是最后一个部分, Vue
中 style
部分的代码规范。到此 Vue
代码规范已经完结,希望大家能多多点赞,多多支持!
正文
-
为组件样式设置作用域,一般是在
style
标签添加属性scoped
App.vue
顶级组件中,它的样式是全局的。如何解决单组件样式影响全局呢?官方提供了3中解决方案
-
在
style
标签添加属性scoped
-
使用
CSS Modules
来设定CSS
的作用域 -
基于
class
的类似BEM
的策略
// scoped <template> <button class="button button-close">X</button> </template> <!-- 使用 `scoped` attribute --> <style scoped> .button { border: none; border-radius: 2px; } .button-close { background-color: red; } </style> // CSS Modules <template> <button :class="[$style.button, $style.buttonClose]">X</button> </template> <!-- 使用 CSS Modules --> <style module> .button { border: none; border-radius: 2px; } .buttonClose { background-color: red; } </style> // BEM <template> <button class="c-Button c-Button--close">X</button> </template> <!-- 使用 BEM 约定 --> <style> .c-Button { border: none; border-radius: 2px; } .c-Button--close { background-color: red; } </style>
-
-
不允许使用
元素选择器
在
scoped
样式中,类选择器比元素选择器更好,因为大量使用元素选择器是很慢的。// Bad <template> <p>this is text</p> </template> <style scoped> p { color: red; } </style> // Good <template> <p class="text">this is text</p> </template> <style scoped> .text { color: red; } </style>
-
属性顺序
属性应该按照特定的顺序出现保证代码的易读性;
class
是为了高可复用组件设计的,所以应该处于第一位;id
更加具体且应该尽量少使用,所以应该放在第二位。class
id
name
data-*
src
for
type
src
href
value
max-length
max
min
pattern
placeholder
title
alt
aria-*
role
required
readonly
disabled
<a class="..." id="..." data-modal="toggle" href="#">Example link</a> <input class="form-control" type="text"> <img src=".." alt="...">
-
boolean
属性boolean
属性存在表示取值为true
, 不存在则表示取值为false
。<input type="text" disabled> <input type="checkbox" value="1" checked> <select> <option value="1" selected>1</option> </select>
-
属性声明顺序
-
位置属性:position top left right z-index display float
-
尺寸大小:width height padding margin
-
背景边框:background border
-
文字系列:font-size line-height letter-spacing color text-align
-
其他: animation transition
-
-
缩进:使用
space
两个空格 -
分号:每个属性声明末尾都要加分号
-
空格
- 以下几种情况不需要空格:
- 属性名后
- 多个规则的分隔符
,
前 !important
的!
后- 属性值中/后/前
- 行末不要有多余的空格
- 以下几种情况需要空格:
- 属性值前/属性名的冒号
:
后 - 选择器
>
+
~
前后 {
前!important
的!
前- 属性值中的
,
后 - 注释内容前后
- 属性值前/属性名的冒号
/* Bad */ .element { color :red! important; background-color: rgba(0,0,0,.5); } /* Good */ .element { color: red !important; background-color: rgba(0, 0, 0, .5); } /* Bad */ .element , .dialog{ } /* Good */ .element, .dialog { } /* Bad */ .element>.dialog{ } /* Good */ .element > .dialog { } /* Bad */ .element{ } /* Good */ .element { }
- 以下几种情况不需要空格:
CSS 常用属性名
header
头部content/container
内容footer
尾部nav
导航sidebar
侧栏column
栏目wrapper
页面外围控制整体布局宽度left right center
左右中loginbar
登录条logo
标志banner
广告main
页面主体hot
热点news
新闻download
下载friendlink
友链cpyright
版权scroll
滚动tags
标签list
文章列表msg
提示信息tips
小技巧title
栏目标题joinus
计入我们guide
指南service
服务register
注册status
状态vote
投票