Vue3代碼風(fēng)格推薦從入門到精通
目錄結(jié)構(gòu)
my-vue3-project/ ├── src/ │ ├── assets/ # 靜態(tài)資源(圖片、字體等) │ ├── components/ │ │ ├── common/ # 通用UI組件(跨項(xiàng)目復(fù)用,無業(yè)務(wù)邏輯) │ │ │ └── BaseButton.vue │ │ └── biz/ # 通用業(yè)務(wù)組件(跨頁面復(fù)用,含業(yè)務(wù)邏輯) │ │ └── BizUserCard.vue │ ├── composables/ # 組合式函數(shù)(可復(fù)用的狀態(tài)邏輯) │ │ └── useUser.ts │ ├── layouts/ # 布局組件(頁面整體結(jié)構(gòu)) │ │ ├── default.vue │ │ └── components/ # 布局專用組件(僅布局層使用) │ │ └── AppHeader.vue │ ├── pages/ # 頁面組件(路由對(duì)應(yīng),kebab-case命名) │ │ ├── user-profile.vue │ │ └── user/ # 頁面模塊 │ │ ├── list.vue │ │ └── components/ # 頁面專用組件(僅當(dāng)前模塊使用) │ │ └── UserFilter.vue │ ├── router/ # 路由配置(管理頁面路由) │ │ ├── index.ts │ │ └── user-routes.ts │ ├── stores/ # Pinia狀態(tài)管理(全局共享狀態(tài)) │ │ └── userStore.ts │ ├── services/ # API服務(wù)層(封裝后端接口調(diào)用) │ │ └── userService.ts │ ├── utils/ # 工具函數(shù)(純函數(shù),無副作用) │ │ ├── formatDate.ts │ │ └── validateEmail.ts │ ├── types/ # TypeScript類型定義(接口、枚舉等) │ │ ├── User.ts │ │ └── api.ts │ ├── styles/ # 全局樣式(變量、混入、重置樣式) │ │ └── global.scss │ ├── App.vue │ └── main.ts ├── tests/ │ └── unit/ # 單元測(cè)試(與src目錄結(jié)構(gòu)對(duì)應(yīng)) │ ├── components/ │ └── utils/ └── package.json
文件命名規(guī)則
| 類型 | 規(guī)則 | 示例 | 說明 |
|---|---|---|---|
| 通用UI組件 | Base + PascalCase | BaseButton.vue | 無業(yè)務(wù)邏輯,純UI |
| 通用業(yè)務(wù)組件 | Biz + PascalCase | BizUserCard.vue | 跨頁面復(fù)用,含業(yè)務(wù) |
| 布局組件 | App + PascalCase | AppHeader.vue | 僅布局層使用 |
| 頁面文件 | kebab-case | user-profile.vue | 與路由路徑一致 |
| 頁面專用組件 | PascalCase | UserFilter.vue | 僅當(dāng)前模塊使用 |
| 組合式函數(shù) | use + camelCase | useUser.ts | 邏輯復(fù)用 |
| Store | camelCase + Store | userStore.ts | 全局狀態(tài) |
| Service | camelCase + Service | userService.ts | API封裝 |
| 工具函數(shù) | camelCase | formatDate.ts | 純函數(shù) |
| 類型定義 | PascalCase | User.ts | 接口/枚舉 |
| 測(cè)試文件 | 源文件名 + .spec.ts | BaseButton.spec.ts | 單元測(cè)試 |
組件編寫
組件分類與命名
| 組件類型 | 目錄 | 命名規(guī)則 | 示例 |
|---|---|---|---|
| 通用UI組件 | components/common/ | Base + PascalCase | BaseButton.vue |
| 通用業(yè)務(wù)組件 | components/biz/ | Biz + PascalCase | BizUserCard.vue |
| 布局組件 | layouts/components/ | App + PascalCase | AppHeader.vue |
| 頁面專用組件 | pages/xxx/components/ | PascalCase | UserFilter.vue |
單文件組件結(jié)構(gòu)
<script setup lang="ts">
// 1. 類型導(dǎo)入
import type { UserInfo } from '@/types/User'
// 2. 第三方庫
import { ElMessage } from 'element-plus'
// 3. 組件導(dǎo)入
import BaseButton from '@/components/common/BaseButton.vue'
// 4. 工具/組合式函數(shù)
import { useUser } from '@/composables/useUser'
// 5. Props
interface Props {
userId: string
title?: string
}
const props = withDefaults(defineProps<Props>(), {
title: '默認(rèn)'
})
// 6. Emits
const emit = defineEmits<{
(e: 'update', user: UserInfo): void
}>()
// 7. 響應(yīng)式數(shù)據(jù)
const loading = ref(false)
// 8. 計(jì)算屬性
const displayName = computed(() => user.value?.name)
// 9. 方法
async function fetchUser() {}
// 10. 生命周期
onMounted(() => {})
// 11. 暴露
defineExpose({ refresh: fetchUser })
</script>
<template>
<!-- 自定義組件:PascalCase;第三方:kebab-case -->
<BaseButton @click="handleClick" />
<el-button type="primary" />
</template>
<style scoped lang="scss">
// BEM命名
.user-card {
&__header {}
&--active {}
}
</style>模板使用規(guī)則
| 組件類型 | 模板中寫法 | 示例 |
|---|---|---|
| 自定義組件 | PascalCase | <BaseButton /> |
| 第三方UI庫 | kebab-case | <el-button /> |
| 原生HTML | 小寫 | <div /> |
組合式函數(shù)模板
// composables/useCounter.ts
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const doubled = computed(() => count.value * 2)
function increment() { count.value++ }
function reset() { count.value = initialValue }
return { count, doubled, increment, reset }
}要點(diǎn):以
use開頭,返回響應(yīng)式狀態(tài)和方法
狀態(tài)管理與 API 服務(wù)
Store 規(guī)范(Pinia)
文件樹示例
stores/ ├── userStore.ts ├── cartStore.ts └── productStore.ts
模板
// stores/userStore.ts
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: '',
isLoggedIn: false
}),
getters: {
displayName: (state) => state.name || '游客'
},
actions: {
async login(email: string, password: string) {
// 登錄邏輯
},
logout() {
this.$reset()
}
}
})組件中使用
<script setup>
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/userStore'
const userStore = useUserStore()
// 狀態(tài)用 storeToRefs 解構(gòu)保持響應(yīng)性
const { name, displayName } = storeToRefs(userStore)
// actions 直接解構(gòu)
const { login, logout } = userStore
</script>要點(diǎn):狀態(tài)使用
storeToRefs解構(gòu),actions 可直接解構(gòu)
Service 規(guī)范
文件樹示例
services/
├── userService.ts
├── productService.ts
└── api/
├── client.ts # axios實(shí)例配置
└── interceptors.ts # 攔截器模板
// services/userService.ts
import request from './api/client'
import type { UserInfo, LoginParams } from '@/types/User'
export const userService = {
async getUser(id: string): Promise<UserInfo> {
const { data } = await request.get(`/api/users/${id}`)
return data
},
async login(params: LoginParams): Promise<{ token: string }> {
const { data } = await request.post('/api/users/login', params)
return data
}
}要點(diǎn):只負(fù)責(zé) API 調(diào)用,不包含 UI 邏輯,明確返回類型
工具函數(shù)與類型定義
工具函數(shù)規(guī)范
文件樹示例
utils/ ├── formatDate.ts # 日期格式化 ├── formatCurrency.ts # 貨幣格式化 ├── validateEmail.ts # 郵箱驗(yàn)證 └── storage.ts # 本地存儲(chǔ)封裝
模板
// utils/formatDate.ts
export function formatDate(date: Date, format = 'YYYY-MM-DD'): string {
const d = new Date(date)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return format
.replace('YYYY', String(year))
.replace('MM', month)
.replace('DD', day)
}
// utils/validateEmail.ts
export function validateEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@([^\s@.,]+\.)+[^\s@.,]{2,}$/
return emailRegex.test(email)
}要點(diǎn):純函數(shù)無副作用,一個(gè)文件一個(gè)功能,避免創(chuàng)建
utils.ts萬能文件
類型定義規(guī)范
文件樹示例
types/ ├── User.ts # 用戶相關(guān)類型 ├── Product.ts # 商品相關(guān)類型 ├── api.ts # API通用類型 └── global.d.ts # 全局類型聲明
模板
// types/User.ts
export interface UserInfo {
id: string
name: string
email: string
role: UserRole
}
export enum UserRole {
Admin = 'admin',
User = 'user'
}
// types/api.ts
export interface ApiResponse<T = unknown> {
code: number
message: string
data: T
}使用方式
// ? 正確:使用 type 關(guān)鍵字導(dǎo)入純類型
import type { UserInfo } from '@/types/User'
// ? 正確:枚舉需要值導(dǎo)入
import { UserRole } from '@/types/User'要點(diǎn):使用
type關(guān)鍵字導(dǎo)入純類型,枚舉需要值導(dǎo)入
測(cè)試規(guī)范
文件樹示例
tests/unit/
├── components/
│ ├── common/
│ │ └── BaseButton.spec.ts
│ └── biz/
│ └── BizUserCard.spec.ts
├── composables/
│ └── useCounter.spec.ts
├── stores/
│ └── userStore.spec.ts
├── services/
│ └── userService.spec.ts
└── utils/
└── formatDate.spec.ts組件測(cè)試模板
// tests/unit/components/common/BaseButton.spec.ts
import { mount } from '@vue/test-utils'
import BaseButton from '@/components/common/BaseButton.vue'
describe('BaseButton', () => {
it('renders correctly', () => {
const wrapper = mount(BaseButton, {
slots: { default: 'Click' }
})
expect(wrapper.text()).toBe('Click')
})
it('emits click event when clicked', async () => {
const wrapper = mount(BaseButton)
await wrapper.trigger('click')
expect(wrapper.emitted('click')).toBeTruthy()
})
})組合式函數(shù)測(cè)試模板
// tests/unit/composables/useCounter.spec.ts
import { useCounter } from '@/composables/useCounter'
describe('useCounter', () => {
it('initializes with default value', () => {
const { count } = useCounter()
expect(count.value).toBe(0)
})
it('increments count correctly', () => {
const { count, increment } = useCounter(5)
increment()
expect(count.value).toBe(6)
})
})工具函數(shù)測(cè)試模板
// tests/unit/utils/formatDate.spec.ts
import { formatDate } from '@/utils/formatDate'
describe('formatDate', () => {
it('formats date with default format', () => {
const date = new Date(2024, 0, 15)
expect(formatDate(date)).toBe('2024-01-15')
})
it('formats date with custom format', () => {
const date = new Date(2024, 0, 15)
expect(formatDate(date, 'YYYY/MM/DD')).toBe('2024/01/15')
})
})要點(diǎn):測(cè)試文件與源文件同名 +
.spec.ts,目錄結(jié)構(gòu)與src/對(duì)應(yīng)
組件庫封裝范式
基礎(chǔ)版
<script lang="ts" setup>
import type { InputInstance, InputProps } from 'element-plus'
import { getCurrentInstance } from 'vue'
import type { ExtractPropTypes } from 'vue'
// 1. 定義 Props 類型(繼承 Element Plus Input 的所有屬性)
export interface CustomInputProps extends ExtractPropTypes<InputProps> {
title?: string // 自定義標(biāo)題
}
// 2. 定義實(shí)例類型(繼承原始實(shí)例 + 自定義方法)
export interface CustomInputInstance extends InputInstance {
someClick: () => void
}
defineOptions({
inheritAttrs: false // 手動(dòng)控制屬性透?jìng)?
})
// 3. Props 默認(rèn)值
const props = withDefaults(defineProps<CustomInputProps>(), {
title: '自定義封裝的Input',
clearable: true // 覆蓋默認(rèn)值為 true
})
// 4. 事件定義
const emit = defineEmits<{
(e: 'titleClick'): void
}>()
const vm = getCurrentInstance()
// 5. ref 回調(diào):合并原始實(shí)例和自定義方法
function changeRef(inputInstance: Record<string, any> | null) {
if (vm) {
vm.exposeProxy = vm.exposed = Object.assign(inputInstance || {}, {
someClick
}) as CustomInputInstance
}
}
function someClick() {
console.log('someClick')
}
function handleTitleClick() {
emit('titleClick')
}
// 6. 暴露合并后的實(shí)例
defineExpose((vm?.exposeProxy || {}) as CustomInputInstance)
</script>
<template>
<div class="custom-input">
<div @click="handleTitleClick">{{ title }}</div>
<!-- 透?jìng)魉袑傩院筒宀?-->
<el-input :ref="changeRef" v-bind="{ ...$attrs, ...props }">
<template v-for="(_, name) in $slots" :key="name" #[name]="slotProps">
<slot :name="name" v-bind="slotProps" />
</template>
</el-input>
</div>
</template>h 函數(shù)版
<script lang="ts" setup>
import { getCurrentInstance, h } from 'vue'
import { ElInput } from 'element-plus'
import type { InputInstance, InputProps } from 'element-plus'
import type { ExtractPropTypes } from 'vue'
export interface CustomInputProps extends ExtractPropTypes<InputProps> {
title?: string
}
export interface CustomInputInstance extends InputInstance {
someClick: () => void
}
defineOptions({
inheritAttrs: false
})
const props = withDefaults(defineProps<CustomInputProps>(), {
title: '自定義封裝的Input',
clearable: true
})
const emit = defineEmits<{
(e: 'titleClick'): void
}>()
const vm = getCurrentInstance()
function changeRef(inputInstance: Record<string, any> | null) {
if (vm) {
vm.exposeProxy = vm.exposed = Object.assign(inputInstance || {}, {
someClick
})
}
}
function someClick() {
console.log('someClick')
}
function handleTitleClick() {
emit('titleClick')
}
defineExpose((vm?.exposeProxy || {}) as CustomInputInstance)
</script>
<template>
<div class="custom-input">
<div @click="handleTitleClick">{{ title }}</div>
<!-- h 函數(shù)渲染,自動(dòng)處理插槽透?jìng)?-->
<component :is="h(ElInput, { ...$attrs, ...props, ref: changeRef }, $slots)" />
</div>
</template>總結(jié)
到此這篇關(guān)于Vue3代碼風(fēng)格推薦從入門到精通的文章就介紹到這了,更多相關(guān)Vue3代碼風(fēng)格推薦內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue路由組件的緩存keep-alive和include屬性的具體使用
:瀏覽器頁面在進(jìn)行切換時(shí),原有的路由組件會(huì)被銷毀,通過緩存可以保存被切換的路由組件,本文主要介紹了Vue路由組件的緩存keep-alive和include屬性的具體使用,感興趣的可以了解一下2023-11-11
vue實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Grid拖拽布局
這篇文章主要為大家詳細(xì)介紹了如何利用vue實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Grid拖拽布局,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
Element input樹型下拉框的實(shí)現(xiàn)代碼
這篇文章主要介紹了Element input樹型下拉框的實(shí)現(xiàn)代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12
vue中axios防止多次觸發(fā)終止多次請(qǐng)求的示例代碼(防抖)
這篇文章主要介紹了vue中axios防止多次觸發(fā)終止多次請(qǐng)求的實(shí)現(xiàn)方法(防抖),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02
使用vue-cli導(dǎo)入Element UI組件的方法
這篇文章給大家介紹了使用vue-cli導(dǎo)入Element UI組件的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友一起看看吧2018-05-05

