Vant 風格指南

2020-02-05 09:41 更新

介紹

在參與 Vant 開發(fā)時,請遵守約定的單文件組件風格指南,指南內容節(jié)選自 Vue 官方風格指南。

組件數據

組件的 data 必須是一個函數。

// bad
export default {
  data: {
    foo: 'bar'
  }
}

// good
export default {
  data () {
    return {
      foo: 'bar'
    }
  }
}

單文件組件文件名稱

單文件組件的文件名應該要么始終是單詞大寫開頭 (PascalCase),要么始終是橫線連接 (kebab-case)。

// bad
mycomponent.vue
myComponent.vue

// good
my-component.vue
MyComponent.vue

緊密耦合的組件名

和父組件緊密耦合的子組件應該以父組件名作為前綴命名。

// bad
components/
|- TodoList.vue
|- TodoItem.vue
└─ TodoButton.vue

// good
components/
|- TodoList.vue
|- TodoListItem.vue
└─ TodoListItemButton.vue

自閉合組件

在單文件組件中沒有內容的組件應該是自閉合的。

<!-- bad -->
<my-component></my-component>

<!-- good -->
<my-component />

Prop 名大小寫

在聲明 prop 的時候,其命名應該始終使用 camelCase,而在模板中應該始終使用 kebab-case。

// bad
export default {
  props: {
    'greeting-text': String
  }
};

// good
export default {
  props: {
    greetingText: String
  }
}
<!-- bad -->
<welcome-message greetingText="hi" />

<!-- good -->
<welcome-message greeting-text="hi" />

Props 換行

多個 Props 的元素應該分多行撰寫,每個 Props 一行,閉合標簽單起一行。

<!-- bad -->
<my-component foo="a" bar="b" baz="c" />

<!-- good -->
<my-component
  foo="a"
  bar="b"
  baz="c"
/>

指令縮寫

指令縮寫,用 : 表示 v-bind: ,用 @ 表示 v-on:

<!-- bad -->
<input
  v-bind:value="value"
  v-on:input="onInput"
>

<!-- good -->
<input
  :value="value"
  @input="onInput"
>

Props 順序

標簽的 Props 應該有統一的順序,依次為指令、屬性和事件。

<my-component
  v-if="if"
  v-show="show"
  v-model="value"
  ref="ref"
  :key="key"
  :text="text"
  @input="onInput"
  @change="onChange"
/>

組件選項的順序

組件選項應該有統一的順序。

export default {
  name: '',

  mixins: [],

  components: {},

  props: {},

  data() {},

  computed: {},

  watch: {},

  created() {},

  mounted() {},

  destroyed() {},

  methods: {}
};

組件選項中的空行

組件選項較多時,建議在屬性之間添加空行。

export default {
  computed: {
    formattedValue() {
      // ...
    },

    styles() {
      // ...
    }
  },

  methods: {
    onInput() {
      // ...
    },

    onChange() {
      // ...
    }
  }
};

單文件組件頂級標簽的順序

單文件組件應該總是讓頂級標簽的順序保持一致,且標簽之間留有空行。

<template>
...
</template>

<script>
/* ... */
</script>

<style>
/* ... */
</style>


實例演示

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號