Vue前端开发规范( 二 )


单文件组件的文件名应该要么始终是单词大写开头 (PascalCase)
正例:
components/|- MyComponent.vue复制代码反例:
components/|- myComponent.vue|- mycomponent.vue复制代码3. 基础组件名
应用特定样式和约定的基础组件 (也就是展示类的、无逻辑的或无状态的组件) 应该全部以一个特定的前缀开头,比如 Base、App 或 V 。
正例:
components/|- BaseButton.vue|- BaseTable.vue|- BaseIcon.vue复制代码反例:
components/|- MyButton.vue|- VueTable.vue|- Icon.vue复制代码【Vue前端开发规范】4. 单例组件名
只应该拥有单个活跃实例的组件应该以 The 前缀命名,以示其唯一性 。
这不意味着组件只可用于一个单页面,而是每个页面只使用一次 。这些组件永远不接受任何 prop,因为它们是为你的应用定制的,而不是它们在你的应用中的上下文 。如果你发现有必要添加 prop,那就表明这实际上是一个可复用的组件,只是目前在每个页面里只使用一次 。
正例:
components/|- TheHeading.vue|- TheSidebar.vue复制代码反例:
components/|- Heading.vue|- MySidebar.vue复制代码5. 紧密耦合的组件名
和父组件紧密耦合的子组件应该以父组件名作为前缀命名 。
如果一个组件只在某个父组件的场景下有意义,这层关系应该体现在其名字上 。因为编辑器通常会按字母顺序组织文件,所以这样做可以把相关联的文件排在一起 。
正例:
components/|- TodoList.vue|- TodoListItem.vue|- TodoListItemButton.vuecomponents/|- SearchSidebar.vue|- SearchSidebarNavigation.vue复制代码反例:
components/|- SearchSidebar.vue|- NavigationForSearchSidebar.vue复制代码6. 组件名中的单词顺序
组件名应该以高级别的 (通常是一般化描述的) 单词开头,以描述性的修饰词结尾 。
正例:
components/|- SearchButtonClear.vue|- SearchButtonRun.vue|- SearchInputQuery.vue|- SearchInputExcludeGlob.vue|- SettingsCheckboxTerms.vue|- SettingsCheckboxLaunchOnStartup.vue复制代码反例:
components/|- ClearSearchButton.vue|- ExcludeFromSearchInput.vue|- LaunchOnStartupCheckbox.vue|- RunSearchButton.vue|- SearchInput.vue|- TermsCheckbox.vue复制代码7. 模板中的组件名大小写
总是 PascalCase 的
正例:
<!-- 在单文件组件和字符串模板中 --><MyComponent/>复制代码反例:
<!-- 在单文件组件和字符串模板中 --><mycomponent/><!-- 在单文件组件和字符串模板中 --><myComponent/>复制代码8. 完整单词的组件名
组件名应该倾向于完整单词而不是缩写 。
正例:
components/|- StudentDashboardSettings.vue|- UserProfileOptions.vue复制代码反例:
components/|- SdSettings.vue|- UProfOpts.vue复制代码9. 多个特性的元素
多个特性的元素应该分多行撰写,每个特性一行 。
正例:
<img src=https://www.isolves.com/it/cxkf/bk/2021-03-10/"https://vuejs.org/images/logo.png" alt="Vue Logo">复制代码反例:
<img src=https://www.isolves.com/it/cxkf/bk/2021-03-10/"https://vuejs.org/images/logo.png" alt="Vue Logo">复制代码10. 模板中简单的表达式
组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法 。
复杂表达式会让你的模板变得不那么声明式 。我们应该尽量描述应该出现的是什么,而非如何计算那个值 。而且计算属性和方法使得代码可以重用 。
正例:
<!-- 在模板中 -->{{ normalizedFullName }}// 复杂表达式已经移入一个计算属性computed: { normalizedFullName: function () { return this.fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') }}复制代码反例:
{{ fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ')}}复制代码11. 简单的计算属性
正例:
computed: { basePrice: function () { return this.manufactureCost / (1 - this.profitMargin) }, discount: function () { return this.basePrice * (this.discountPercent || 0) }, finalPrice: function () { return this.basePrice - this.discount }}复制代码反例:
computed: { price: function () { var basePrice = this.manufactureCost / (1 - this.profitMargin) return ( basePrice - basePrice * (this.discountPercent || 0) ) }}复制代码


推荐阅读