组件文件:使用 PascalCase
命名法,如 UserProfile.vue
。
工具函数文件:使用 camelCase
命名法,如 dateUtils.js
。
样式文件:使用 kebab-case
命名法,如 global-styles.scss
。
<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, }, }, |
使用 scoped
属性来限制样式作用域,避免全局污染。
<style scoped> .user-profile { /* 样式 */ } </style> |
推荐使用 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'); |
将 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
。
将 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; |
使用 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
进行代码格式化,保持代码风格一致。
{ "singleQuote": true, "semi": false, "trailingComma": "es5" } |