关于vue.js:Vue前端开发规范

34次阅读

共计 8257 个字符,预计需要花费 21 分钟才能阅读完成。

基于 Vue 官网格调指南整顿

一、强制

  1. 组件名为多个单词
    组件名应该始终是多个单词的,根组件 App 除外。

正例:

export default {
name: ‘TodoItem’,
// …
}
复制代码
反例:

export default {
name: ‘Todo’,
// …
}
复制代码

  1. 组件数据
    组件的 data 必须是一个函数。
    当在组件中应用 data 属性的时候 (除了 new Vue 外的任何中央),它的值必须是返回一个对象的函数。

正例:

// In a .vue file
export default {
data () {

return {foo: 'bar'}

}
}
// 在一个 Vue 的根实例上间接应用对象是能够的,
// 因为只存在一个这样的实例。
new Vue({
data: {

foo: 'bar'

}
})
复制代码
反例:

export default {
data: {

foo: 'bar'

}
}
复制代码

  1. Prop 定义
    Prop 定义应该尽量具体。
    在你提交的代码中,prop 的定义应该尽量具体,至多须要指定其类型。

正例:

props: {
status: String
}
// 更好的做法!
props: {
status: {

type: String,
required: true,
validator: function (value) {
  return [
    'syncing',
    'synced',
    'version-conflict',
    'error'
  ].indexOf(value) !== -1
}

}
}
复制代码
反例:

// 这样做只有开发原型零碎时能够承受
props: [‘status’]
复制代码

  1. 为 v -for 设置键值
    总是用 key 配合 v-for。
    在组件上_总是_必须用 key 配合 v-for,以便保护外部组件及其子树的状态。甚至在元素上保护可预测的行为,比方动画中的对象固化 (object constancy),也是一种好的做法。

正例:

<ul>
<li

v-for="todo in todos"
:key="todo.id"
{{todo.text}}

</li>
</ul>
复制代码
反例:

<ul>
<li v-for=”todo in todos”>

{{todo.text}}

</li>
</ul>
复制代码
5. 防止 v-if 和 v-for 用在一起
永远不要把 v-if 和 v-for 同时用在同一个元素上。
个别咱们在两种常见的状况下会偏向于这样做:

为了过滤一个列表中的我的项目 (比方 v-for=”user in users” v-if=”user.isActive”)。在这种情景下,请将 users 替换为一个计算属性 (比方 activeUsers),让其返回过滤后的列表。
为了防止渲染本应该被暗藏的列表 (比方 v-for=”user in users” v-if=”shouldShowUsers”)。这种情景下,请将 v-if 挪动至容器元素上 (比方 ul, ol)。
正例:

<ul v-if=”shouldShowUsers”>
<li

v-for="user in users"
:key="user.id"
{{user.name}}

</li>
</ul>
复制代码
反例:

<ul>
<li

v-for="user in users"
v-if="shouldShowUsers"
:key="user.id"
{{user.name}}

</li>
</ul>
复制代码

  1. 为组件款式设置作用域
    对于利用来说,顶级 App 组件和布局组件中的款式能够是全局的,然而其它所有组件都应该是有作用域的。
    这条规定只和单文件组件无关。你不肯定要应用 scoped 个性。设置作用域也能够通过 CSS Modules,那是一个基于 class 的相似 BEM 的策略,当然你也能够应用其它的库或约定。

不管怎样,对于组件库,咱们应该更偏向于选用基于 class 的策略而不是 scoped 个性。

这让覆写外部款式更容易:应用了常人可了解的 class 名称且没有太高的选择器优先级,而且不太会导致抵触。
正例:

<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>
复制代码
反例:

<template>
<button class=”btn btn-close”>X</button>
</template>

<style>
.btn-close {
background-color: red;
}
</style>

<template>
<button class=”button button-close”>X</button>
</template>

<!– 应用 scoped 个性 –>
<style scoped>
.button {
border: none;
border-radius: 2px;
}

.button-close {
background-color: red;
}
</style>
复制代码
二、强烈推荐(加强可读性)

  1. 组件文件
    只有有可能拼接文件的构建零碎,就把每个组件独自分成文件。
    当你须要编辑一个组件或查阅一个组件的用法时,能够更疾速的找到它。

正例:

components/
|- TodoList.vue
|- TodoItem.vue
复制代码
反例:

Vue.component(‘TodoList’, {
// …
})

Vue.component(‘TodoItem’, {
// …
})
复制代码

  1. 单文件组件文件的大小写
    单文件组件的文件名应该要么始终是单词大写结尾 (PascalCase)

正例:

components/
|- MyComponent.vue
复制代码
反例:

components/
|- myComponent.vue
|- mycomponent.vue
复制代码

  1. 根底组件名
    利用特定款式和约定的根底组件 (也就是展现类的、无逻辑的或无状态的组件) 应该全副以一个特定的前缀结尾,比方 Base、App 或 V。

正例:

components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
复制代码
反例:

components/
|- MyButton.vue
|- VueTable.vue
|- Icon.vue
复制代码

  1. 单例组件名
    只应该领有单个沉闷实例的组件应该以 The 前缀命名,以示其唯一性。
    这不意味着组件只可用于一个单页面,而是每个页面只应用一次。这些组件永远不承受任何 prop,因为它们是为你的利用定制的,而不是它们在你的利用中的上下文。如果你发现有必要增加 prop,那就表明这实际上是一个可复用的组件,只是目前在每个页面里只应用一次。

正例:

components/
|- TheHeading.vue
|- TheSidebar.vue
复制代码
反例:

components/
|- Heading.vue
|- MySidebar.vue
复制代码

  1. 严密耦合的组件名
    和父组件严密耦合的子组件应该以父组件名作为前缀命名。
    如果一个组件只在某个父组件的场景下有意义,这层关系应该体现在其名字上。因为编辑器通常会按字母程序组织文件,所以这样做能够把相关联的文件排在一起。

正例:

components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
components/
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue
复制代码
反例:

components/
|- SearchSidebar.vue
|- NavigationForSearchSidebar.vue
复制代码

  1. 组件名中的单词程序
    组件名应该以高级别的 (通常是一般化形容的) 单词结尾,以描述性的修饰词结尾。

正例:

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
复制代码

  1. 模板中的组件名大小写
    总是 PascalCase 的

正例:

<!– 在单文件组件和字符串模板中 –>
<MyComponent/>
复制代码
反例:

<!– 在单文件组件和字符串模板中 –>
<mycomponent/>
<!– 在单文件组件和字符串模板中 –>
<myComponent/>
复制代码

  1. 残缺单词的组件名
    组件名应该偏向于残缺单词而不是缩写。

正例:

components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
复制代码
反例:

components/
|- SdSettings.vue
|- UProfOpts.vue
复制代码

  1. 多个个性的元素
    多个个性的元素应该分多行撰写,每个个性一行。

正例:

<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”/>
复制代码

  1. 模板中简略的表达式
    组件模板应该只蕴含简略的表达式,简单的表达式则应该重构为计算属性或办法。
    简单表达式会让你的模板变得不那么申明式。咱们应该尽量形容应该呈现的是什么,而非如何计算那个值。而且计算属性和办法使得代码能够重用。

正例:

<!– 在模板中 –>
{{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(‘ ‘)
}}
复制代码

  1. 简略的计算属性
    正例:

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)
)

}
}
复制代码

  1. 带引号的个性值
    非空 HTML 个性值应该始终带引号 (单引号或双引号,选你 JS 里不必的那个)。
    在 HTML 中不带空格的个性值是能够没有引号的,但这样做经常导致带空格的特征值被回避,导致其可读性变差。

正例:

<AppSidebar :style=”{width: sidebarWidth + ‘px’}”>
复制代码
反例:

<AppSidebar :style={width:sidebarWidth+’px’}>
复制代码

  1. 指令缩写
    都用指令缩写 (用 : 示意 v-bind: 和用 @ 示意 v-on:)

正例:

<input
@input=”onInput”
@focus=”onFocus”

复制代码
反例:

<input
v-bind:value=”newTodoText”
:placeholder=”newTodoInstructions”

复制代码
三、举荐

  1. 单文件组件的顶级元素的程序
    单文件组件应该总是让 <script>、<template> 和 <style> 标签的程序保持一致。且 <style> 要放在最初,因为另外两个标签至多要有一个。

正例:

<!– ComponentA.vue –>
<template>…</template>
<script>//</script>
<style>//</style>
复制代码
四、审慎应用 (有潜在危险的模式)

  1. 没有在 v-if/v-if-else/v-else 中应用 key
    如果一组 v-if + v-else 的元素类型雷同,最好应用 key (比方两个 <div> 元素)。

正例:

<div
v-if=”error”
key=”search-status”

谬误:{{error}}
</div>
<div
v-else
key=”search-results”

{{results}}
</div>
复制代码
反例:

<div v-if=”error”>
谬误:{{error}}
</div>
<div v-else>
{{results}}
</div>
复制代码

  1. scoped 中的元素选择器
    元素选择器应该防止在 scoped 中呈现。
    在 scoped 款式中,类选择器比元素选择器更好,因为大量应用元素选择器是很慢的。

正例:

<template>
<button class=”btn btn-close”>X</button>
</template>

<style scoped>
.btn-close {
background-color: red;
}
</style>
复制代码
反例:

<template>
<button>X</button>
</template>

<style scoped>
button {
background-color: red;
}
</style>
复制代码

  1. 隐性的父子组件通信
    应该优先通过 prop 和事件进行父子组件之间的通信,而不是 this.$parent 或扭转 prop。

正例:

Vue.component(‘TodoItem’, {
props: {

todo: {
  type: Object,
  required: true
}

},
template: `

<input
  :value="todo.text"
  @input="$emit('input', $event.target.value)"
>

`
})
复制代码
反例:

Vue.component(‘TodoItem’, {
props: {

todo: {
  type: Object,
  required: true
}

},
methods: {

removeTodo () {
  var vm = this
  vm.$parent.todos = vm.$parent.todos.filter(function (todo) {return todo.id !== vm.todo.id})
}

},
template: `

<span>
  {{todo.text}}
  <button @click="removeTodo">
    X
  </button>
</span>

`
})
复制代码

  1. 非 Flux 的全局状态治理
    应该优先通过 Vuex 治理全局状态,而不是通过 this.$root 或一个全局事件总线。

正例:

// store/modules/todos.js
export default {
state: {

list: []

},
mutations: {

REMOVE_TODO (state, todoId) {state.list = state.list.filter(todo => todo.id !== todoId)
}

},
actions: {

removeTodo ({commit, state}, todo) {commit('REMOVE_TODO', todo.id)
}

}
}
<!– TodoItem.vue –>
<template>
<span>

{{todo.text}}
<button @click="removeTodo(todo)">
  X
</button>

</span>
</template>

<script>
import {mapActions} from ‘vuex’

export default {
props: {

todo: {
  type: Object,
  required: true
}

},
methods: mapActions([‘removeTodo’])
}
</script>
复制代码
反例:

// main.js
new Vue({
data: {

todos: []

},
created: function () {

this.$on('remove-todo', this.removeTodo)

},
methods: {

removeTodo: function (todo) {
  var todoIdToRemove = todo.id
  this.todos = this.todos.filter(function (todo) {return todo.id !== todoIdToRemove})
}

}
})
复制代码
附录

  1. 举荐应用 vs code 进行前端编码,规定 Tab 大小为 2 个空格
    vs code 配置
    {
    “editor.tabSize”: 2,
    “workbench.startupEditor”: “newUntitledFile”,
    “workbench.iconTheme”: “vscode-icons”,
    // 以下为 stylus 配置
    “stylusSupremacy.insertColons”: false, // 是否插入冒号
    “stylusSupremacy.insertSemicolons”: false, // 是否插入分好
    “stylusSupremacy.insertBraces”: false, // 是否插入大括号
    “stylusSupremacy.insertNewLineAroundImports”: false, // import 之后是否换行
    “stylusSupremacy.insertNewLineAroundBlocks”: false, // 两个选择器中是否换行
    “vetur.format.defaultFormatter.html”: “js-beautify-html”,
    “eslint.autoFixOnSave”: true,
    “eslint.validate”: [
    “javascript”,
    {
    “language”: “html”,
    “autoFix”: true
    },
    {
    “language”: “vue”,
    “autoFix”: true
    },
    “javascriptreact”,
    “html”,
    “vue”
    ],
    “eslint.options”: {“plugins”: [“html”] },
    “prettier.singleQuote”: true,
    “prettier.semi”: false,
    “javascript.format.insertSpaceBeforeFunctionParenthesis”: false,
    “vetur.format.js.InsertSpaceBeforeFunctionParenthesis”: false,
    “vetur.format.defaultFormatter.js”: “prettier”,
    // “prettier.eslintIntegration”: true
    }
    复制代码
    vs code 插件
    Auto Close Tag
    Path Intellisense
    Prettier
    Vetur
    vscode-icons
    最初
    如果你感觉此文对你有一丁点帮忙,点个赞。或者能够退出我的开发交换群:1025263163 互相学习,咱们会有业余的技术答疑解惑

如果你感觉这篇文章对你有点用的话,麻烦请给咱们的开源我的项目点点 star: https://gitee.com/ZhongBangKe… 不胜感激!

正文完
 0