學會VUE的這些編碼規範,讓你的代碼質量提升一個等級

編碼規範看看起來和實現項目功能並沒有太大的聯繫,但是爲什麼它還是顯得如此的重要呢。它主要有三大要素:可讀性,可維護性,可變更性。

一個團隊統一了編碼規範,可以大大的提高開發效率與交互效率,可以很容易的看懂他人寫的代碼,使後期的維護也變得更加簡單。今天來講講VUE只的編碼規範。分爲三個等級:必要的、強烈推薦、謹慎使用

一、必要的

1. 組件名爲多個單詞,而不是一個單詞

反例


Vue.component('todo', {
  // ...
})
export default {
  name: 'Todo',
  // ...
}

正例

Vue.component('todo-item', {
  // ...
})
export default {
  name: 'TodoItem',
  // ...
}

2. 組件的data必須是一個函數

反例

export default {
  data: {
    name: 'dzy'
  }
}

正例

export default {
  data() {
    return {
      name: 'dzy'    
    }
  }
}

3. prop的定義應該儘量詳細,至少需要指定類型

反例

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. 把每個組件獨立成一個文件**

反例
```javascript
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**

反例
```javascript
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. 應該把複雜的計算屬性,分割爲極可能多的計算屬性**
反例
```javascript
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或一個全局事件總線

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章