1. 组件名为多个单词,避免跟现有以及未来的 html
元素相冲突
<BaseComponent />
2. props
定义,尽可能详细
props: {
status: {
type: String,
default: "1",
required: true
}
}
3. 在组件上总是必须用 key
配合 v-for
4. 永远不要把 v-if
和 v-for
同时用在同一个元素上
当 Vue 处理指令时,v-for
比 v-if
具有更高的优先级,导致每次重渲染的时候会遍历整个列表`
5. 为组件样式设置作用域
<style scoped>
.name {
color: #999999;
}
</style>
6. 单文件组件文件名采用单词大写开头
<BaseComponent />
7. 基础组件名(例如自定义按钮、表格、输入框),以一个特定的前缀开头,比如 Base
、App
或 V
等
<BaseButton />
<AppButton />
<VButton />
8. 单例组件名(不接受props
,自己私人定制的组件),以The
为开头
<TheButton />
9. 子组件应该以父组件名作为前缀命名
IDE通常会按字母顺序组织文件,所以这样可以把相关联的文件排在一起
components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
10.组件名中的单词顺序,以一般化描述的单词开头,以描述性的修饰词结尾
在自然的英文里,形容词和其它描述语通常都出现在名词之前
// 反例
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
11. 自闭合组件
<!-- 反例 -->
<MyComponent></MyComponent>
<!-- 好例子 -->
<MyComponent />
12. 组件名是完整单词而不是缩写
<!-- 反例 -->
<SdSettings />
<!-- 好例子 -->
<StudentDashboardSettings />
13. 指令都使用缩写形式
<input :value="newTodoText"/>
14. 组件模板只包含简单的表达式,复杂的表达式则应为计算属性或方法。
/** 反例 */
<div>
{{
fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}}
</div>
/** 好例子 */
<div>{{ normalizedFullName }}</div>
computed: {
normalizedFullName: function () {
return this.fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}
}
15. 选项式API顺序
components:
props
data
computed
watch
/** 生命周期钩子 */
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
activated
deactivated
beforeDestroy
destroyed
/** 方法 */
methods