Vue-代码规范
Mar 14, 2018
组件名为多个单词
好例子
Vue.component('todo-item', {
// ...
})
export default {
name: 'TodoItem',
// ...
}
组件的 data 必须是一个函数。
好例子
// In a .vue file
export default {
data () {
return {
foo: 'bar'
}
}
}
Prop 定义应该尽量详细。
好例子
props: {
status: String
}
更好的做法!
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
为 v-for 设置键值
好例子
<ul>
<li
v-for="todo in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
</ul>
永远不要把 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>
<li
v-for="user in activeUsers"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
<ul v-if="shouldShowUsers">
<li
v-for="user in users"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
为组件样式设置作用域
好例子
<template>
<button class="button button-close">X</button>
</template>
<!-- 使用 `scoped` 特性 -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
.button-close {
background-color: red;
}
</style>
<template>
<button :class="[$style.button, $style.buttonClose]">X</button>
</template>
<!-- 使用 CSS Modules -->
<style module>
.button {
border: none;
border-radius: 2px;
}
.buttonClose {
background-color: red;
}
</style>
<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>
私有属性名
在插件、混入等扩展中始终为自定义的私有属性使用 $_ 前缀。并附带一个命名空间以回避和其它作者的冲突 (比如 $yourPluginName)。
Vue 使用 _ 前缀来定义其自身的私有属性,所以使用相同的前缀 (比如 _update) 有覆写实例属性的风险。即便你检查确认 Vue 当前版本没有用到这个属性名,也不能保证和将来的版本没有冲突。
对于 $ 前缀来说,其在 Vue 生态系统中的目的是暴露给用户的一个特殊的实例属性,所以把它用于私有属性并不合适。
不过,我们推荐把这两个前缀结合为 $_,作为一个用户定义的私有属性的约定,以确保不会和 Vue 自身相冲突。
好例子
var myGreatMixin = {
// ...
methods: {
$_myGreatMixin_update: function () {
// ...
}
}
}
组件/实例的选项的顺序
1.副作用 (触发组件外的影响)
- el
2.全局感知 (要求组件以外的知识)
- name
- parent
3.组件类型 (更改组件的类型)
- functional
4.模板修改器 (改变模板的编译方式)
- delimiters
- comments
5.模板依赖 (模板内使用的资源)
- components
- directives
- filters
6.组合 (向选项里合并属性)
- extends
- mixins
7.接口 (组件的接口)
- inheritAttrs
- model
- props/propsData
8.本地状态 (本地的响应式属性)
- data
- computed
9.事件 (通过响应式事件触发的回调)
- watch
- 生命周期钩子 (按照它们被调用的顺序)
10.非响应式的属性 (不依赖响应系统的实例属性)
- methods
11.渲染 (组件输出的声明式描述)
- template/render
- renderError