Vue精简版风格概述

2020-06-16 06:08:12易采站长站整理


//bad
<!-- 在单文件组件和字符串模板中 -->
<mycomponent/>
<myComponent/>
<!-- 在 DOM 模板中 -->
<MyComponent></MyComponent>
//good
<!-- 在单文件组件和字符串模板中 -->
<MyComponent/>
<!-- 在 DOM 模板中 -->
<my-component></my-component>

【组件名应该倾向于完整单词而不是缩写】(强烈推荐)


//bad
components/
|- SdSettings.vue
|- UProfOpts.vue
//good
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue

组件相关

【单文件组件、字符串模板和JSX中没有内容的组件应该自闭合——但在DOM模板里不要这样做】(强烈推荐)

自闭合组件表示它们不仅没有内容,而且刻意没有内容


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

【为组件样式设置作用域】(必要)

这条规则只和单文件组件有关。不一定要使用 

scoped
 特性。设置作用域也可以通过 CSS Modules,或者使用其它的库或约定


//bad
<template><button class="btn btn-close">X</button></template>
<style>
.btn-close {background-color: red;}
</style>
//good
<template><button class="btn btn-close">X</button></template>
<style scoped>
.btn-close {background-color: red;}
</style>
//good
<template><button :class="[$style.button, $style.buttonClose]">X</button></template>
<style module>
.btn-close {background-color: red;}
</style>

【单文件组件应该总是让 <script>、<template> 和 <style> 标签的顺序保持一致】(推荐)


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

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

【一个文件中只有一个组件】(强烈推荐)


//bad
Vue.component('TodoList', {})
Vue.component('TodoItem', {})
//good