優先順序C規則:推薦
當存在多個同等好的選項時,可以任意選擇以確保一致性。在這些規則中,我們描述了每個可接受的選項,並建議一個預設選擇。這意味著你可以在自己的程式碼庫中自由地做出不同的選擇,只要保持一致並且有合理的理由。不過,請確保有合理的理由!透過適應社群標準,你將
- 訓練你的大腦,以便更容易地解析你遇到的社群程式碼的大部分內容
- 能夠複製貼上大多數社群程式碼示例,無需修改
- 通常發現新入職員工已經習慣了你的首選編碼風格,至少在Vue方面
元件/例項選項順序
元件/例項選項應該有序排列。
這是我們推薦的元件選項預設順序。它們被分為類別,這樣你就知道在哪裡新增來自外掛的屬性。
全域性意識(需要超出元件的知識)
name
模板編譯器選項(改變模板的編譯方式)
compilerOptions
模板依賴(模板中使用的資產)
components
directives
組合(將屬性合併到選項中)
extends
mixins
provide
/inject
介面(元件的介面)
inheritAttrs
props
emits
組合式API(使用組合式API的入口點)
setup
本地狀態(區域性響應式屬性)
data
computed
事件(由響應式事件觸發的回撥函式)
watch
- 生命週期事件(按呼叫順序)
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
activated
deactivated
beforeUnmount
unmounted
errorCaptured
renderTracked
renderTriggered
非響應式屬性(獨立於響應式系統的例項屬性)
methods
渲染(元件輸出的宣告性描述)
template
/render
元素屬性順序
元素的屬性(包括元件)應該有序排列。
這是我們推薦的元件選項預設順序。它們被分為類別,這樣你就知道在哪裡新增自定義屬性和指令。
定義(提供元件選項)
is
列表渲染(建立相同元素的多個變體)
v-for
條件(元素是否渲染/顯示)
v-if
v-else-if
v-else
v-show
v-cloak
渲染修飾符(改變元素渲染方式)
v-pre
v-once
全域性意識(需要超出元件的知識)
id
唯一屬性(需要唯一值的屬性)
ref
key
雙向繫結(結合繫結和事件)
v-model
其他屬性(所有未指定的繫結和未繫結屬性)
事件(元件事件監聽器)
v-on
內容(覆蓋元素的原始內容)
v-html
v-text
元件/例項選項中的空行
您可能希望在多行屬性之間新增一個空行,尤其是如果選項在螢幕上無法顯示而需要滾動時。
當元件開始顯得擁擠或難以閱讀時,在多行屬性之間新增空格可以使它們更容易瀏覽。在某些編輯器中,如Vim,這種格式選項也可以使它們更容易用鍵盤導航。
不良
js
defineProps({
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
})
const formattedValue = computed(() => {
// ...
})
const inputClasses = computed(() => {
// ...
})
良好
js
defineProps({
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
})
const formattedValue = computed(() => {
// ...
})
const inputClasses = computed(() => {
// ...
})
單檔案元件頂層元素順序
單檔案元件 應始終按順序排列 <script>
、<template>
和 <style>
標籤,其中 <style>
最後,因為其中至少有一個是必需的。
不良
template
<style>/* ... */</style>
<script>/* ... */</script>
<template>...</template>
template
<!-- ComponentA.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
良好
template
<!-- ComponentA.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
template
<!-- ComponentA.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>