1.文件命名
组件文件:使用
PascalCase
命名法,如UserProfile.vue
。工具函数文件:使用
camelCase
命名法,如dateUtils.js
。样式文件:使用
kebab-case
命名法,如global-styles.scss
。
2.Vue 组件规范
组件结构
<template> <div class="user-profile"> <!-- 模板内容 --> </div> </template> <script> export default { name: 'UserProfile', // 组件名使用 PascalCase components: { // 引入的子组件 }, props: { // 定义 props }, data() { return { // 组件数据 }; }, computed: { // 计算属性 }, watch: { // 监听器 }, methods: { // 方法 }, created() { // 生命周期钩子 }, mounted() { // 生命周期钩子 }, }; </script> <style scoped> .user-profile { /* 样式 */ } </style>
组件命名
props: { userName: { type: String, required: true, }, age: { type: Number, default: 18, }, },
3.样式规范
Scoped CSS
使用
scoped
属性来限制样式作用域,避免全局污染。
<style scoped> .user-profile { /* 样式 */ } </style>
CSS 预处理器
推荐使用
SCSS
或Less
作为 CSS 预处理器。
<style lang="less" scoped> .user-profile { .avatar { width: 100px; height: 100px; } } </style>
路由规范
使用
kebab-case
命名路由路径。
const routes = [ { path: '/user-profile', name: 'UserProfile', component: UserProfile, }, ];
路由懒加载
使用
import()
语法实现路由懒加载。
const UserProfile = () => import('@/views/UserProfile.vue');
4.Vuex 规范
模块化
将 Vuex 模块化,每个模块放在
store/modules/
目录下。
// store/modules/user.js const state = { userInfo: null, }; const mutations = { SET_USER_INFO(state, userInfo) { state.userInfo = userInfo; }, }; const actions = { fetchUserInfo({ commit }) { // 异步操作 }, }; export default { namespaced: true, state, mutations, actions, };
命名规范
Mutation 类型:使用
UPPER_SNAKE_CASE
命名法,如SET_USER_INFO
。Action 命名:使用
camelCase
命名法,如fetchUserInfo
。
5.API 请求规范
接口封装
将 API 请求封装在
api/
目录下,按模块划分。
// api/user.js import request from '@/utils/request'; export function fetchUserInfo(userId) { return request({ url: `/user/${userId}`, method: 'get', }); }
请求方法
使用
axios
进行请求,并在utils/request.js
中进行全局配置。
// utils/request.js import axios from 'axios'; const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, timeout: 5000, }); service.interceptors.request.use( config => { // 请求拦截 return config; }, error => { // 请求错误处理 return Promise.reject(error); } ); service.interceptors.response.use( response => { // 响应拦截 return response.data; }, error => { // 响应错误处理 return Promise.reject(error); } ); export default service;
6.代码质量规范
ESLint
使用
ESLint
进行代码质量检查,推荐使用eslint-plugin-vue
插件。
{ "extends": [ "plugin:vue/essential", "eslint:recommended" ], "rules": { "vue/no-unused-components": "warn", "vue/no-unused-vars": "warn", "no-console": "warn" } }
Prettier
使用
Prettier
进行代码格式化,保持代码风格一致。
{ "singleQuote": true, "semi": false, "trailingComma": "es5" }
添加评论