个人网站: www.dzyong.top
公众号: 【前端筱园】
做者:邓占勇
编码规范看看起来和实现项目功能并无太大的联系,可是为何它仍是显得如此的重要呢。它主要有三大要素:可读性,可维护性,可变动性。javascript
一个团队统一了编码规范,能够大大的提升开发效率与交互效率,能够很容易的看懂他人写的代码,使后期的维护也变得更加简单。今天来说讲VUE只的编码规范。分为三个等级:必要的、强烈推荐、谨慎使用前端
1. 组件名为多个单词,而不是一个单词vue
反例java
Vue.component('todo', { // ... }) export default { name: 'Todo', // ... }
正例ide
Vue.component('todo-item', { // ... }) export default { name: 'TodoItem', // ... }
2. 组件的data必须是一个函数函数
反例网站
export default { data: { name: 'dzy' } }
正例ui
export default { data() { return { name: 'dzy' } } }
3. prop的定义应该尽可能详细,至少须要指定类型this
反例编码
props: ['status']
正例
props:{ name: { type: String, default: 'dzy', required: true } }
4. 为v-for设置键值,老是用key配合v-for
反例
<ul> <li v-for="todo in todos"> {{ todo.text }} </li> </ul>
正例
<ul> <li v-for="todo in todos" :key="todo.id" > {{ todo.text }} </li> </ul>
5. 永远不要把v-if与v-for用在同一个元素上
反例
<ul> <li v-for="user in users" v-if="shouldShowUsers" :key="user.id" > {{ user.name }} </li> </ul>
正例
<ul v-if="shouldShowUsers"> <li v-for="user in users" :key="user.id" > {{ user.name }} </li> </ul>
6. 为组件样式设置做用域
反例
<style> .btn-close { background-color: red; } </style> 正例 <style scoped> .button { border: none; border-radius: 2px; } </style>
7. 私有属性名
Vue 使用 _ 前缀来定义其自身的私有属性,因此使用相同的前缀 (好比 _update) 有覆写实例属性的风险。即使你检查确认 Vue 当前版本没有用到这个属性名,也不能保证和未来的版本没有冲突。
对于 $ 前缀来讲,其在 Vue 生态系统中的目的是暴露给用户的一个特殊的实例属性,因此把它用于私有属性并不合适。
不过,咱们推荐把这两个前缀结合为 $_,做为一个用户定义的私有属性的约定,以确保不会和 Vue 自身相冲突。
正例
var myGreatMixin = { // ... methods: { update: function () { // ... } } } var myGreatMixin = { // ... methods: { _update: function () { // ... } } } var myGreatMixin = { // ... methods: { $update: function () { // ... } } }
正例
var myGreatMixin = { // ... methods: { $_myGreatMixin_update: function () { // ... } } } // 甚至更好! var myGreatMixin = { // ... methods: { publicMethod() { // ... myPrivateFunction() } } } function myPrivateFunction() { // ... } export default myGreatMixin
1. 把每一个组件独立成一个文件
反例
Vue.component('TodoList', { // ... }) Vue.component('TodoItem', { // ... })
正例
components/ |- TodoList.vue |- TodoItem.vue
2. 单文件的组件名必定是大写开头或者以“-”链接
反例
components/ |- mycomponent.vue components/ |- myComponent.vue
正例
components/ |- MyComponent.vue components/ |- my-component.vue
3. 特定样式或基础组件,应该以同一个公共前缀开头
反例
components/ |- MyButton.vue |- VueTable.vue |- Icon.vue
正例
components/ |- BaseButton.vue |- BaseTable.vue |- BaseIcon.vue components/ |- AppButton.vue |- AppTable.vue |- AppIcon.vue
4. 若是一个组件是一个定制组件,即它不是一个公共组件,这种组件名应以The开头,表示惟一性,它不该该接收任何prop,若是接收prop那么说明它是一个公共组件
反例
components/ |- Heading.vue |- MySidebar.vue
正例
components/ |- TheHeading.vue |- TheSidebar.vue
5.和父组件紧密耦合子组件,应以父组件名做为前缀名
反例
components/ |- TodoList.vue |- TodoItem.vue |- TodoButton.vue
正例
components/ |- TodoList.vue |- TodoListItem.vue |- TodoListItemButton.vue
6. 组件名应以高级别的单词开头,以描述性的修饰词结尾
反例
components/ |- ClearSearchButton.vue |- ExcludeFromSearchInput.vue |- LaunchOnStartupCheckbox.vue |- RunSearchButton.vue |- SearchInput.vue |- TermsCheckbox.vue
正例
components/ |- SearchButtonClear.vue |- SearchButtonRun.vue |- SearchInputQuery.vue |- SearchInputExcludeGlob.vue |- SettingsCheckboxTerms.vue |- SettingsCheckboxLaunchOnStartup.vue
7. 在单文件组件、字符模板和JSX中没有内容的组件应该是自闭和的,可是在DOM模板里永远不要这么作
反例
<!-- 在单文件组件、字符串模板和 JSX 中 --> <MyComponent></MyComponent> <!-- 在 DOM 模板中 --> <my-component/>
正例
<!-- 在单文件组件、字符串模板和 JSX 中 --> <MyComponent/> <!-- 在 DOM 模板中 --> <my-component></my-component>
8. JS/JSX中的组件名应为驼峰命名
反例
Vue.component('myComponent', { // ... }) import myComponent from './MyComponent.vue' export default { name: 'myComponent', // ... } export default { name: 'my-component', // ... }
正例
Vue.component('MyComponent', { // ... }) Vue.component('my-component', { // ... }) import MyComponent from './MyComponent.vue' export default { name: 'MyComponent', // ... }
9. 组件名应为完整的英文单词,而不是缩写
反例
components/ |- SdSettings.vue |- UProfOpts.vue
正例
components/ |- StudentDashboardSettings.vue |- UserProfileOptions.vue ``` **v10. 在声明prop的时候,名称应为驼峰命名,而在模板和JSX应用中应该是kebab-case** 反例
props: {
'greeting-text': String
}
<WelcomeMessage greetingText="hi"/>
正例
props: {
greetingText: String
}
<WelcomeMessage greeting-text="hi"/>
**11. 多个attribute的元素应该分多行撰写,每一个attribute一行** 反例
<img src="https://vuejs.org/images/logo.png" alt="Vue Logo">
<MyComponent foo="a" bar="b" baz="c"/>
正例
<img
src="https://vuejs.org/images/logo.png"
alt="Vue Logo"
<MyComponent
foo="a"
bar="b"
baz="c"
/>
**12. 组件模板应该只包含简单的表达式,复杂的表达式应该重构为计算属性或方法** 反例
{{
fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}}
正例
<!-- 在模板中 -->
{{ normalizedFullName }}
// 复杂表达式已经移入一个计算属性
computed: {
normalizedFullName: function () {
return this.fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ')
}
}
`
13. 应该把复杂的计算属性,分割为很可能多的计算属性
反例
computed: { price: function () { var basePrice = this.manufactureCost / (1 - this.profitMargin) return ( basePrice - basePrice * (this.discountPercent || 0) ) } }
正例
computed: { basePrice: function () { return this.manufactureCost / (1 - this.profitMargin) }, discount: function () { return this.basePrice * (this.discountPercent || 0) }, finalPrice: function () { return this.basePrice - this.discount } }
14. 非空的attitude值应该始终带引号
反例
<input type=text> <AppSidebar :style={width:sidebarWidth+'px'}> 正例 <input type="text"> <AppSidebar :style="{ width: sidebarWidth + 'px' }">
15. 指令能够缩写的建议缩写
<input v-bind:value="newTodoText" :placeholder="newTodoInstructions" > <input v-on:input="onInput" @focus="onFocus" > <template v-slot:header> <h1>Here might be a page title</h1> </template> <template #footer> <p>Here's some contact info</p> </template>
欢迎访问个人网站:www.dzyong.top,关注个人公众号【前端筱园】,不错过个人每一篇推送
1. 同一组的v-if和v-else最好使用key标识
什么意思呢,咱们咋使用v-if和v-else时,都是成组出现的,当咱们在一个上下文中,屡次使用到v-if和v-else,这很容易引发混乱,很难看出那个v-else是属于那个v-else的。添加key标识还能够提升更新DOM的效率
<div v-if="error" key="search-status" > 错误:{{ error }} </div> <div v-else key="search-results" > {{ results }} </div>
2. 元素选择器应该避免在scoped 中出现
在scoped样式中,类选择器比元素选择器很好,大量使用元素选择器是很慢的。
这是由于VUE在为了给样式设置做用域,vue会为元素添加一个惟一的attribute,以下图所示。而后修改选择器,使得元素选择器的元素中,只有带这个attribute的元素才会生效,因此大量使用元素+attribute组合的选择器,比类+attribute组合的选择器所涉及的元素更多,也就致使更慢。
3. 应该优先使用prop进行父子组件间的通讯,而不是使用this$parent或改变prop
4. 应该优先使用VUEX管理全局状态,而不是经过this.$root或一个全局事件总线