Vue3.0时代:你不知道的风格指南

学习了一段时间的Vue3.0,发现了官网真的是宝藏,总结了一篇风格指南的学习过程,希望可以给你们的开发带来便捷。

1.必要的

  • 组件名应该是多个单词组合,避免和现有的和未来将要有的组件冲突
export default {
  name: 'TodoItem',
  // ...
}
  • prop定义尽量地详细一些
props: {
  status: String
}

// 更好的例子
props: {
  status: {
    type: String,
    required: true,

    validator: value => {
      return [
        'syncing',
        'synced',
        'version-conflict',
        'error'
      ].includes(value)
    }
  }
}
  • 为v-for设置key值
<ul>
  <li
    v-for="todo in todos"
    :key="todo.id"
  >
    {{ todo.text }}
  </li>
</ul>
  • 避免v-for和v-if在一个元素上一起使用,因为俩者的优先级不同,在vue3中v-if优先级高,每次渲染都会先循环再进行条件判断,浪费掉性能。
//推荐使用
<ul v-if="shouldShowUsers">
  <li
    v-for="user in users"
    :key="user.id"
  >
    {{ user.name }}
  </li>
</ul>

//不建议使用
<ul>
  <li
    v-for="user in users"
    v-if="shouldShowUsers"
    :key="user.id"
  >
    {{ user.name }}
  </li>
</ul>
  • 组件样式设置作用域,防止同一个组件不同样式互相覆盖,设置一致的作用域会确保你的样式只会运用在它们想要作用的组件上。
<!-- 使用 `scoped` attribute -->
<style scoped>
.button {
  border: none;
  border-radius: 2px;
}
</style>
<!-- 使用 CSS modules -->
<style module>
.button {
  border: none;
  border-radius: 2px;
}
</style>
<template>
  <button class="c-Button c-Button--close">×</button>
</template>

<!-- 使用 BEM 约定 -->
<style>
.c-Button {
  border: none;
  border-radius: 2px;
}

.c-Button--close {
  background-color: red;
}
</style>
  • 使用模块作用域保持不允许外部访问的函数的私有性。如果无法做到这一点,就始终为插件、混入等不考虑作为对外公共 API 的自定义私有 property 使用 $_ 前缀。并附带一个命名空间以回避和其它作者的冲突 (比如 $_yourPluginName_)。

    const myGreatMixin = {
      // ...
      methods: {
        $_myGreatMixin_update() {
          // ...
        }
      }
    }
    
    // Even better!
    const myGreatMixin = {
      // ...
      methods: {
        publicMethod() {
          // ...
          myPrivateFunction()
        }
      }
    }
    
    function myPrivateFunction() {
      // ...
    }
    
    export default myGreatMixin
    

2.强烈推荐

只要有能够拼接文件的构建系统,就把每个组件单独分成文件,方便快速查阅编辑。

components/
|- TodoList.js
|- TodoItem.js
components/
|- TodoList.vue
|- TodoItem.vue

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

components/
|-   MyComponent.vue
|-   my-component.vue

应用特定样式和约定的基础组件 (也就是展示类的、无逻辑的或无状态的组件) 应该全部以一个特定的前缀开头,比如 BaseAppV

components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
components/
|- AppButton.vue
|- AppTable.vue
|- AppIcon.vue
components/
|- VButton.vue
|- VTable.vue
|- VIcon.vue

只应该拥有单个活跃实例的组件应该以 The 前缀命名,以示其唯一性。

components/
|- TheHeading.vue
|- TheSidebar.vue

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

components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue

组件名称应该以高阶的 (通常是一般化描述的) 单词开头,以描述性的修饰词结尾。

components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue

在单文件组件字符串模板和JSX中没有内容的组件应该是自闭合的——但在 DOM 模板里永远不要这样做。

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

对于绝大多数项目来说,在单文件组件和字符串模板中组件名称应该总是 PascalCase 的——但是在 DOM 模板中总是 kebab-case 的。

<!-- 在单文件组件和字符串模板中 -->
<MyComponent/>
<!-- 在 DOM 模板中            -->
<my-component></my-component>
<!-- 在所有地方 -->
<my-component></my-component>

JS/JSX 中的组件名应该始终是 PascalCase 的,尽管在较为简单的应用中只使用 app.component 进行全局组件注册时,可以使用 kebab-case 字符串。

app.component('MyComponent', {
  // ...
})
app.component('my-component', {
  // ...
})
import MyComponent from './MyComponent.vue'
export default {
  name: 'MyComponent',
  // ...
}

组件名称应该倾向于完整单词而不是缩写。

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

props: {
  greetingText: String
}
<WelcomeMessage greeting-text="hi"/>

**多个 attribute 的元素应该分多行撰写,每个 attribute 一行。

<MyComponent
  foo="a"
  bar="b"
  baz="c"
/>

组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法。

<!-- 在模板中 -->
{{ normalizedFullName }}
// 复杂表达式已经移入一个计算属性
computed: {
  normalizedFullName() {
    return this.fullName.split(' ')
      .map(word => word[0].toUpperCase() + word.slice(1))
      .join(' ')
  }
}
//不建议如下写法
{{
  fullName.split(' ').map((word) => {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')
}}

应该把复杂计算属性分割为尽可能多的更简单的 property。

computed: {
  basePrice() {
    return this.manufactureCost / (1 - this.profitMargin)
  },

  discount() {
    return this.basePrice * (this.discountPercent || 0)
  },

  finalPrice() {
    return this.basePrice - this.discount
  }
}

//不建议使用以下写法
computed: {
  price() {
    const basePrice = this.manufactureCost / (1 - this.profitMargin)
    return (
      basePrice -
      basePrice * (this.discountPercent || 0)
    )
  }
}

非空 HTML attribute 值应该始终带引号 (单引号或双引号,选你 JS 里不用的那个)

<AppSidebar :style="{ width: sidebarWidth + 'px' }">

指令缩写 (用 : 表示 v-bind:@ 表示 v-on: 和用 # 表示 v-slot) 应该要么都用要么都不用。

<template #header>
  <h1>Here might be a page title</h1>
   <input
  v-on:input="onInput"
  v-on:focus="onFocus"
>
<input
  v-bind:value="newTodoText"
  v-bind:placeholder="newTodoInstructions"
>
</template>

3.推荐

1.单文件组件应该总是让 <script><template><style> 标签的顺序保持一致。且 <style> 要放在最后,因为另外两个标签至少要有一个。

2.可能想在多个 property 之间增加一个空行,特别是在这些选项一屏放不下,需要滚动才能都看到的时候。

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

3.组件选项默认顺序。

  1. 全局感知 (要求组件以外的知识)
    • name
  2. 模板依赖 (模板内使用的资源)
    • components
    • directives
  3. 组合 (向选项里合并 property)
    • extends
    • mixins
    • provide/inject
  4. 接口 (组件的接口)
    • inheritAttrs
    • props
    • emits
  5. 组合式 API (使用组合式 API 的入口点)
    • setup
  6. 本地状态 (本地的响应式 property)
    • data
    • computed
  7. 事件 (通过响应式事件触发的回调)
    • watch
    • 生命周期钩子 (按照它们被调用的顺序)
      • beforeCreate
      • created
      • beforeMount
      • mounted
      • beforeUpdate
      • updated
      • activated
      • deactivated
      • beforeUnmount
      • unmounted
      • errorCaptured
      • renderTracked
      • renderTriggered
  8. 非响应式的 property (不依赖响应性系统的实例 property)
    • methods
  9. 渲染 (组件输出的声明式描述)
    • template/render

元素 (包括组件) 的 attribute 应该有统一的顺序。

  1. 定义 (提供组件的选项)
    • is
  2. 列表渲染 (创建多个变化的相同元素)
    • v-for
  3. 条件渲染 (元素是否渲染/显示)
    • v-if
    • v-else-if
    • v-else
    • v-show
    • v-cloak
  4. 渲染修饰符 (改变元素的渲染方式)
    • v-pre
    • v-once
  5. 全局感知 (需要超越组件的知识)
    • id
  6. 唯一的 Attributes (需要唯一值的 attribute)
    • ref
    • key
  7. 双向绑定 (把绑定和事件结合起来)
    • v-model
  8. 其他 Attributes (所有普通的绑定或未绑定的 attribute)
  9. 事件 (组件事件监听器)
    • v-on
  10. 内容 (覆写元素的内容)
    • v-html
    • v-text

4.谨慎使用

元素选择器应该避免在 scoped 中出现。

应该优先通过 prop 和事件进行父子组件之间的通信,而不是 this.$parent 或变更 prop。

app.component('TodoItem', {
  props: {
    todo: {
      type: Object,
      required: true
    }
  },

  template: `
    <input
      :value="todo.text"
      @input="$emit('input', $event.target.value)"
    >
  `
})
app.component('TodoItem', {
  props: {
    todo: {
      type: Object,
      required: true
    }
  },

  template: `
    <span>
      {{ todo.text }}
      <button @click="$emit('delete')">
        ×
      </button>
    </span>
  `
})

应该优先通过Vuex管理全局状态,而不是通过 this.$root 或一个全局事件总线。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值