基本规范
这些规则有助于防止错误,因此请不惜一切代价学习并遵守这些规则。 例外可能存在,但应该非常罕见,并且只能由具有 JavaScript 和 Vue 专业知识的人进行。
使用多词组件名称
用户组件名称应始终为多字,但 root 除外 App 组件。 这 可以防止 与现有和将来的 HTML 元素发生冲突,因为所有 HTML 元素都是一个单词。
//坏
<!-- in pre-compiled templates -->
<Item /><!-- in in-DOM templates -->
<item></item>//好
<!-- in pre-compiled templates -->
<TodoItem /><!-- in in-DOM templates -->
<todo-item></todo-item>
使用详细的道具定义
在提交的代码中,prop 定义应始终尽可能详细,至少指定类型。
//坏
// This is only OK when prototyping
const props = defineProps(['status'])//好
// Even better!
const props = defineProps({status: {type: String,required: true,validator: (value) => {return ['syncing', 'synced', 'version-conflict', 'error'].includes(value)}}
})
使用键控 v-for
key 跟 v-for 在 组件上始终 是必需的,以便维护子树下方的内部组件状态。 不过,即使对于元素,保持可预测的行为也是一种很好的做法,例如 动画中的对象恒定 性。
//坏
<ul><li v-for="todo in todos">{{ todo.text }}</li>
</ul>//好
<ul><liv-for="todo in todos":key="todo.id">{{ todo.text }}</li>
</ul>
避免 v-if 跟 v-for
从不使用 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><liv-for="user in users"v-if="user.isActive":key="user.id">{{ user.name }}</li>
</ul>//好
<ul><liv-for="user in activeUsers":key="user.id">{{ user.name }}</li>
</ul><ul><template v-for="user in users" :key="user.id"><li v-if="user.isActive">{{ user.name }}</li></template>
</ul>
使用组件范围的
对于应用程序,顶级样式 App组件和布局组件可以是全局的,但所有其他组件都应始终限定范围。
这仅与 单文件组件 相关。 它不要求 scoped 属性 。 范围界定可以通过 CSS 模块 、基于类的策略(如 井 )或其他库/约定。
但是,组件库应该更喜欢基于类的策略,而不是使用 scoped 属性。
这使得覆盖内部样式变得更加容易,使用人类可读的类名,这些类名没有太高的特异性,但仍然不太可能导致冲突。
//坏
<template><button class="btn btn-close">×</button>
</template><style>
.btn-close {background-color: red;
}
</style>//好
<template><button class="button button-close">×</button>
</template><!-- Using the `scoped` attribute -->
<style scoped>
.button {border: none;border-radius: 2px;
}.button-close {background-color: red;
}
</style>
<template><button :class="[$style.button, $style.buttonClose]">×</button>
</template><!-- Using CSS modules -->
<style module>
.button {border: none;border-radius: 2px;
}.buttonClose {background-color: red;
}
</style>
<template><button class="c-Button c-Button--close">×</button>
</template><!-- Using the BEM convention -->
<style>
.c-Button {border: none;border-radius: 2px;
}.c-Button--close {background-color: red;
}
</style>
后续有其他规范会持续更新,欢迎各位大佬提出建议~~~