Vue规范

# 必要规则(强制要求)
## 组件名应为多个单词
组件名应该始终是多个单词的,根组件 `App` 以及 `<transition>`、`<component>` 之类的 Vue 内置组件除外。

- 正例

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

- 反例

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

## 组件的 `data` 必须是一个函数

- 正例

```html
Vue.component('some-comp', {
  data: function () {
    return {
      foo: 'bar'
    }
  }
})
```
```html
export default {
  data () {
    return {
      foo: 'bar'
    }
  }
}
```

- 反例

```html
Vue.component('some-comp', {
  data: {
    foo: 'bar'
  }
})
```
```html
export default {
  data: {
    foo: 'bar'
  }
}
```

## `props` 定义应该尽量详细

- 正例

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

- 反例

```html
props: ['status']
```

## 为 `v-for` 设置键值
总是用 `key` 配合 `v-for`。

- 正例

```html
<ul>
  <li
    v-for="todo in todos"
    :key="todo.id"
  >
    {{ todo.text }}
  </li>
</ul>
```

- 反例

```html
<ul>
  <li v-for="todo in todos">
    {{ todo.text }}
  </li>
</ul>
```

## 避免 `v-if` 和 `v-for` 用在一起
永远不要把 `v-if` 和 `v-for` 同时用在同一个元素上。

- 正例

```html
<ul v-if="shouldShowUsers">
  <li
    v-for="user in users"
    :key="user.id"
  >
    {{ user.name }}
  </li>
</ul>
```

- 反例

```html
<ul>
  <li
    v-for="user in users"
    v-if="user.isActive"
    :key="user.id"
  >
    {{ user.name }}
  </li>
</ul>
```
```html
<ul>
  <li
    v-for="user in users"
    v-if="shouldShowUsers"
    :key="user.id"
  >
    {{ user.name }}
  </li>
</ul>
```

## 为组件样式设置作用域
对于应用来说,顶级 `App` 组件和布局组件中的样式可以是全局的,但是其它所有组件都应该是有作用域的。

不管怎样,对于组件库,我们应该更倾向于选用基于 class 的策略而不是 `scoped` attribute。

- 正例

```html
<template>
  <button class="button button-close">X</button>
</template>

<!-- 使用 `scoped` attribute -->
<style scoped>
.button {
  border: none;
  border-radius: 2px;
}

.button-close {
  background-color: red;
}
</style>
```
```html
<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>
```
```html
<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>
```

- 反例

```html
<template>
  <button class="btn btn-close">X</button>
</template>

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

## 单文件组件文件的大小写(一个项目中只能使用一种)
单文件组件的文件名应该要么始终是单词大写开头 (PascalCase),要么始终是横线连接 (kebab-case)。

- 正例

```html
components/
|- MyComponent.vue
```
```html
components/
|- my-component.vue
```

- 反例

```html
components/
|- mycomponent.vue
```
```html
components/
|- myComponent.vue
```

## 自闭合组件
在单文件组件、字符串模板和 JSX 中没有内容的组件应该是自闭合的——但在 DOM 模板里永远不要这样做。

- 正例

```html
<!-- 在 JSX 中 -->
<MyComponent/>

<!-- 在单文件组件、字符串模板和 DOM 模板中 -->
<my-component></my-component>
```

- 反例

```html
<!-- 在 JSX 中 -->
<MyComponent></MyComponent>

<!-- 在单文件组件、字符串模板和 DOM 模板中 -->
<my-component/>
```

## 模板中的组件名大小写
对于绝大多数项目来说,在单文件组件和字符串模板中组件名应该总是 PascalCase 的——但是在 DOM 模板中总是 kebab-case 的。

- 正例

```html
<!-- 在 JSX 中 -->
<MyComponent/>

<!-- 在单文件组件、字符串模板和 DOM 模板中 -->
<my-component></my-component>
```

- 反例

```html
<!-- 在 JSX 中 -->
<mycomponent/>
<myComponent/>

<!-- 在单文件组件、字符串模板和 DOM 模板中 -->
<MyComponent></MyComponent>
```

## JS/JSX 中的组件名大小写
JS/JSX 中的组件名应该始终是 PascalCase 的,尽管在较为简单的应用中只使用 `Vue.component` 进行全局组件注册时,可以使用 kebab-case 字符串。

- 正例

```html
Vue.component('MyComponent', {
  // ...
})
```
```html
Vue.component('my-component', {
  // ...
})
```
```html
import MyComponent from './MyComponent.vue'
```
```html
export default {
  name: 'MyComponent',
  // ...
}
```

- 反例

```html
Vue.component('myComponent', {
  // ...
})
```
```html
import myComponent from './MyComponent.vue'
```
```html
export default {
  name: 'myComponent',
  // ...
}
```
```html
export default {
  name: 'my-component',
  // ...
}
```

## `props` 名大小写
在声明 prop 的时候,其命名应该始终使用 camelCase,而在模板和 JSX 中应该始终使用 kebab-case。

- 正例

```html
props: {
  greetingText: String
}

<!-- 在 JSX 中 -->
<WelcomeMessage greeting-text="hi"/>

<!-- 在单文件组件、字符串模板和 DOM 模板中 -->
<welcome-message greeting-text="hi"></welcome-message>
```

- 反例

```html
props: {
  'greeting-text': String
}

<WelcomeMessage greetingText="hi"/>
```

## 非空 HTML attribute 值应该始终带引号

- 正例

```html
<input type="text">
```
```html
<AppSidebar :style="{ width: sidebarWidth + 'px' }">
```

- 反例

```html
<input type=text>
```
```html
<AppSidebar :style={width:sidebarWidth+'px'}>
```

## 指令缩写
指令缩写 (用 `:` 表示 `v-bind:`、用 `@` 表示 `v-on:` 和用 `#` 表示 `v-slot:`) 应该要么都用要么都不用。

- 正例

```html
<!-- 正例 -->
<input
  :value="newTodoText"
  :placeholder="newTodoInstructions"
>
```
```html
<input
  v-bind:value="newTodoText"
  v-bind:placeholder="newTodoInstructions"
>
```
```html
<input
  @input="onInput"
  @focus="onFocus"
>
```
```html
<input
  v-on:input="onInput"
  v-on:focus="onFocus"
>
```
```html
<template v-slot:header>
  <h1>Here might be a page title</h1>
</template>

<template v-slot:footer>
  <p>Here's some contact info</p>
</template>
```
```html
<template #header>
  <h1>Here might be a page title</h1>
</template>

<template #footer>
  <p>Here's some contact info</p>
</template>
```

- 反例

```html
<input
  v-bind:value="newTodoText"
  :placeholder="newTodoInstructions"
>
```
```html
<input
  v-on:input="onInput"
  @focus="onFocus"
>
```
```html
<template v-slot:header>
  <h1>Here might be a page title</h1>
</template>

<template #footer>
  <p>Here's some contact info</p>
</template>
```

## 组件/实例的选项的顺序
组件/实例的选项应该有统一的顺序。
1. 副作用 (触发组件外的影响)
    + el
2. 全局感知 (要求组件以外的知识)
    + name
    + parent
3. 组件类型 (更改组件的类型)
    + functional
4. 模板修改器 (改变模板的编译方式)
    + delimiters
    + comments
5. 模板依赖 (模板内使用的资源)
    + components
    + directives
    + filters
6. 组合 (向选项里合并 property)
    + extends
    + mixins
7. 接口 (组件的接口)
    + inheritAttrs
    + model
    + props/propsData
8. 本地状态 (本地的响应式 property)
    + data
    + computed
9. 事件 (通过响应式事件触发的回调)
    + watch
    + 生命周期钩子 (按照它们被调用的顺序)
        + beforeCreate
        + created
        + beforeMount
        + mounted
        + beforeUpdate
        + updated
        + activated
        + deactivated
        + beforeDestroy
        + destroyed
10. 非响应式的 property (不依赖响应系统的实例 property)
    + methods
11. 渲染 (组件输出的声明式描述)
    + template/render
    + renderError

## 单文件组件的顶级元素的顺序
单文件组件应该总是让 `<template>`、`<script>` 和 `<style>` 标签的顺序保持一致。

- 正例

```html
<!-- ComponentA.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>

<!-- ComponentB.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
```

- 反例

```html
<style>/* ... */</style>
<script>/* ... */</script>
<template>...</template>
```
```html
<!-- ComponentA.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>

<!-- ComponentB.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
```

## 元素选择器应该避免在 `scoped` 中出现

- 正例

```html
<template>
  <button class="btn btn-close">X</button>
</template>

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

- 反例

```html
<template>
  <button>X</button>
</template>

<style scoped>
button {
  background-color: red;
}
</style>
```

## 应该优先通过 prop 和事件进行父子组件之间的通信
应该优先通过 prop 和事件进行父子组件之间的通信,而不是 `this.$parent` 或变更 prop

- 正例

```html
Vue.component('TodoItem', {
  props: {
    todo: {
      type: Object,
      required: true
    }
  },
  template: `
    <input
      :value="todo.text"
      @input="$emit('input', $event.target.value)"
    >
  `
})
```
```html
Vue.component('TodoItem', {
  props: {
    todo: {
      type: Object,
      required: true
    }
  },
  template: `
    <span>
      {{ todo.text }}
      <button @click="$emit('delete')">
        X
      </button>
    </span>
  `
})
```

- 反例

```html
Vue.component('TodoItem', {
  props: {
    todo: {
      type: Object,
      required: true
    }
  },
  template: '<input v-model="todo.text">'
})
```
```html
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>
  `
})
```

## 应该优先通过 Vuex 管理全局状态
应该优先通过 Vuex 管理全局状态,而不是通过 `this.$root` 或一个全局事件总线。

- 正例

```html
// 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)
    }
  }
}
```
```html
<!-- 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>
```

- 反例

```html
// 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
      })
    }
  }
})
```

# 推荐规则(不强制要求)
## 私有 property 名
使用模块作用域保持不允许外部访问的函数的私有性。如果无法做到这一点,就始终为插件、混入等不考虑作为对外公共 API 的自定义私有 property 使用 `$_` 前缀。并附带一个命名空间以回避和其它作者的冲突 (比如 `$_yourPluginName_`)。

- 正例

```html
var myGreatMixin = {
  // ...
  methods: {
    $_myGreatMixin_update: function () {
      // ...
    }
  }
}
```
```html
// 甚至更好!
var myGreatMixin = {
  // ...
  methods: {
    publicMethod() {
      // ...
      myPrivateFunction()
    }
  }
}

function myPrivateFunction() {
  // ...
}

export default myGreatMixin
```

- 反例

```html
var myGreatMixin = {
  // ...
  methods: {
    update: function () {
      // ...
    }
  }
}
```
```html
var myGreatMixin = {
  // ...
  methods: {
    _update: function () {
      // ...
    }
  }
}
```
```html
var myGreatMixin = {
  // ...
  methods: {
    $update: function () {
      // ...
    }
  }
}
```
```html
var myGreatMixin = {
  // ...
  methods: {
    $_update: function () {
      // ...
    }
  }
}
```

## 组件文件

- 正例

```html
components/
|- TodoList.js
|- TodoItem.js
```
```html
components/
|- TodoList.vue
|- TodoItem.vue
```

- 反例

```html
Vue.component('TodoList', {
  // ...
})
```
```html
Vue.component('TodoItem', {
  // ...
})
```

## 基础组件名
应用特定样式和约定的基础组件 (也就是展示类的、无逻辑的或无状态的组件) 应该全部以一个特定的前缀开头,比如 `Base`、`App` 或 `V`。

- 正例

```html
components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
```
```html
components/
|- AppButton.vue
|- AppTable.vue
|- AppIcon.vue
```
```html
components/
|- VButton.vue
|- VTable.vue
|- VIcon.vue
```

- 反例

```html
components/
|- MyButton.vue
|- VueTable.vue
|- Icon.vue
```

## 紧密耦合的组件名
和父组件紧密耦合的子组件应该以父组件名作为前缀命名。

- 正例

```html
components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
```
```html
components/
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue
```

- 反例

```html
components/
|- TodoList.vue
|- TodoItem.vue
|- TodoButton.vue
```
```html
components/
|- SearchSidebar.vue
|- NavigationForSearchSidebar.vue
```

## 完整单词的组件名
组件名应该倾向于完整单词而不是缩写

- 正例

```html
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
```

- 反例

```html
components/
|- SdSettings.vue
|- UProfOpts.vue
```

## 多个 attribute 的元素(一个项目的格式化配置应一致)

- 正例

```html
<img
  src="https://vuejs.org/images/logo.png"
  alt="Vue Logo"
>
```
```html
<MyComponent
  foo="a"
  bar="b"
  baz="c"
/>
```

## 模板中简单的表达式
组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法。

- 正例

```html
<!-- 在模板中 -->
{{ normalizedFullName }}

// 复杂表达式已经移入一个计算属性
computed: {
  normalizedFullName: function () {
    return this.fullName.split(' ').map(function (word) {
      return word[0].toUpperCase() + word.slice(1)
    }).join(' ')
  }
}
```

- 反例

```html
{{
  fullName.split(' ').map(function (word) {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')
}}
```

## 简单的计算属性
应该把复杂计算属性分割为尽可能多的更简单的 property。

- 正例

```html
computed: {
  basePrice: function () {
    return this.manufactureCost / (1 - this.profitMargin)
  },
  discount: function () {
    return this.basePrice * (this.discountPercent || 0)
  },
  finalPrice: function () {
    return this.basePrice - this.discount
  }
}
```

- 反例

```html
computed: {
  price: function () {
    var basePrice = this.manufactureCost / (1 - this.profitMargin)
    return (
      basePrice -
      basePrice * (this.discountPercent || 0)
    )
  }
}
```

## 如果一组 `v-if` + `v-else` 的元素类型相同,最好使用 `key`

- 正例

```html
<div
  v-if="error"
  key="search-status"
>
  错误:{{ error }}
</div>
<div
  v-else
  key="search-results"
>
  {{ results }}
</div>
```

- 反例

```html
<div v-if="error">
  错误:{{ error }}
</div>
<div v-else>
  {{ results }}
</div>
```
posted @ 2020-05-27 10:36  耿鑫  阅读(164)  评论(0编辑  收藏  举报