vue代码规范实现
Vue 代码规范实现
组件命名
组件名应为多个单词,避免与 HTML 元素冲突。使用 PascalCase(大驼峰)命名法,例如 MyComponent.vue。单文件组件的文件名应与组件名一致。
模板结构
模板部分应保持简洁,避免复杂逻辑。使用缩进和换行提高可读性。指令缩写保持一致,例如 v-bind 缩写为 :,v-on 缩写为 @。
<template>
<div class="example">
<button @click="handleClick">Click</button>
</div>
</template>
脚本结构
脚本部分按以下顺序组织:props、data、computed、methods、lifecycle hooks。使用 ES6 语法,例如 const 和箭头函数。
<script>
export default {
name: 'ExampleComponent',
props: {
msg: String
},
data() {
return {
count: 0
}
},
computed: {
doubledCount() {
return this.count * 2
}
},
methods: {
handleClick() {
this.count++
}
},
mounted() {
console.log('Component mounted')
}
}
</script>
样式规范
使用 scoped 属性避免样式污染。推荐使用 CSS 预处理器如 SCSS 或 LESS。类名使用 BEM 命名规范。
<style scoped lang="scss">
.example {
&__button {
background: blue;
}
}
</style>
Props 定义
始终为 props 定义类型和默认值,确保数据流的清晰性。
props: {
size: {
type: String,
default: 'medium',
validator: (value) => ['small', 'medium', 'large'].includes(value)
}
}
事件处理
自定义事件名使用 kebab-case,避免与原生事件冲突。在子组件中通过 $emit 触发事件。
this.$emit('update-data', newData)
状态管理
对于复杂状态,使用 Vuex 或 Pinia。将状态逻辑拆分为模块,保持单一职责原则。
// store/modules/user.js
export default {
state: () => ({
name: ''
}),
mutations: {
SET_NAME(state, name) {
state.name = name
}
}
}
代码分割
使用动态导入实现路由懒加载,提升应用性能。
const UserDetails = () => import('./views/UserDetails.vue')
工具与插件
集成 ESLint 和 Prettier 确保代码风格一致。配置 .eslintrc.js 和 .prettierrc 文件。
// .eslintrc.js
module.exports = {
extends: ['plugin:vue/recommended', 'eslint:recommended'],
rules: {
'vue/multi-word-component-names': 'off'
}
}
测试规范
为组件编写单元测试,使用 Jest 和 Vue Test Utils。覆盖率应达到 80% 以上。

import { mount } from '@vue/test-utils'
import ExampleComponent from './ExampleComponent.vue'
test('increments count on click', async () => {
const wrapper = mount(ExampleComponent)
await wrapper.find('button').trigger('click')
expect(wrapper.vm.count).toBe(1)
})






