风格指南

介绍

在参与 Vant 开发时,请遵守约定的单文件组件风格指南,指南内容节选自 Vue 官方风格指南

组件数据

组件的 data 必须是一个函数。

  1. // bad
  2. export default {
  3. data: {
  4. foo: 'bar'
  5. }
  6. }
  7. // good
  8. export default {
  9. data () {
  10. return {
  11. foo: 'bar'
  12. }
  13. }
  14. }

单文件组件文件名称

单文件组件的文件名应该要么始终是单词大写开头 (PascalCase),要么始终是横线连接 (kebab-case)。

  1. // bad
  2. mycomponent.vue
  3. myComponent.vue
  4. // good
  5. my-component.vue
  6. MyComponent.vue

紧密耦合的组件名

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

  1. // bad
  2. components/
  3. |- TodoList.vue
  4. |- TodoItem.vue
  5. └─ TodoButton.vue
  6. // good
  7. components/
  8. |- TodoList.vue
  9. |- TodoListItem.vue
  10. └─ TodoListItemButton.vue

自闭合组件

在单文件组件中没有内容的组件应该是自闭合的。

  1. <!-- bad -->
  2. <my-component></my-component>
  3. <!-- good -->
  4. <my-component />

Prop 名大小写

在声明 prop 的时候,其命名应该始终使用 camelCase,而在模板中应该始终使用 kebab-case。

  1. // bad
  2. export default {
  3. props: {
  4. 'greeting-text': String
  5. }
  6. };
  7. // good
  8. export default {
  9. props: {
  10. greetingText: String
  11. }
  12. }
  1. <!-- bad -->
  2. <welcome-message greetingText="hi" />
  3. <!-- good -->
  4. <welcome-message greeting-text="hi" />

Props 换行

多个 Props 的元素应该分多行撰写,每个 Props 一行,闭合标签单起一行。

  1. <!-- bad -->
  2. <my-component foo="a" bar="b" baz="c" />
  3. <!-- good -->
  4. <my-component
  5. foo="a"
  6. bar="b"
  7. baz="c"
  8. />

指令缩写

指令缩写,用 : 表示 v-bind: ,用 @ 表示 v-on:

  1. <!-- bad -->
  2. <input
  3. v-bind:value="value"
  4. v-on:input="onInput"
  5. >
  6. <!-- good -->
  7. <input
  8. :value="value"
  9. @input="onInput"
  10. >

Props 顺序

标签的 Props 应该有统一的顺序,依次为指令、属性和事件。

  1. <my-component
  2. v-if="if"
  3. v-show="show"
  4. v-model="value"
  5. ref="ref"
  6. :key="key"
  7. :text="text"
  8. @input="onInput"
  9. @change="onChange"
  10. />

组件选项的顺序

组件选项应该有统一的顺序。

  1. export default {
  2. name: '',
  3. mixins: [],
  4. components: {},
  5. props: {},
  6. data() {},
  7. computed: {},
  8. watch: {},
  9. created() {},
  10. mounted() {},
  11. destroyed() {},
  12. methods: {}
  13. };

组件选项中的空行

组件选项较多时,建议在属性之间添加空行。

  1. export default {
  2. computed: {
  3. formattedValue() {
  4. // ...
  5. },
  6. styles() {
  7. // ...
  8. }
  9. },
  10. methods: {
  11. onInput() {
  12. // ...
  13. },
  14. onChange() {
  15. // ...
  16. }
  17. }
  18. };

单文件组件顶级标签的顺序

单文件组件应该总是让顶级标签的顺序保持一致,且标签之间留有空行。

  1. <template>
  2. ...
  3. </template>
  4. <script>
  5. /* ... */
  6. </script>
  7. <style>
  8. /* ... */
  9. </style>

风格指南  - 图1