Vue 3 最佳实践总结与开发技巧
Vue 3 最佳实践涵盖项目结构配置、Composition API 逻辑复用、响应式系统优化、组件设计与缓存、性能监控与懒加载、国际化、路由管理、状态管理(Pinia)、单元测试、构建部署、安全实践、可访问性、PWA 开发及 SSR/SSG 方案。文章提供 TypeScript 集成、第三方库(Axios/VueUse)使用、动画过渡、动态组件及插件开发指南,并包含电商与资讯网站性能优化案例及迁移策略,旨在提升应用性能、可维护性与用户体验。

Vue 3 最佳实践涵盖项目结构配置、Composition API 逻辑复用、响应式系统优化、组件设计与缓存、性能监控与懒加载、国际化、路由管理、状态管理(Pinia)、单元测试、构建部署、安全实践、可访问性、PWA 开发及 SSR/SSG 方案。文章提供 TypeScript 集成、第三方库(Axios/VueUse)使用、动画过渡、动态组件及插件开发指南,并包含电商与资讯网站性能优化案例及迁移策略,旨在提升应用性能、可维护性与用户体验。

在 Vue 3 的开发旅程中,掌握一系列最佳实践和技巧至关重要。这些实践和技巧不仅能提升开发效率,还能确保应用的性能、可维护性和用户体验达到最佳状态。本文将深入探讨 Vue 3 开发中的关键实践和技巧,帮助开发者在项目中充分发挥 Vue 3 的优势。
一个清晰的项目结构是成功开发的基础。推荐采用以下结构:
src/
├── assets/ # 静态资源
├── components/ # 组件
├── composables/ # 可复用逻辑
├── hooks/ # 自定义钩子
├── layouts/ # 布局
├── router/ # 路由配置
├── stores/ # 状态管理
├── utils/ # 工具函数
├── views/ # 页面组件
├── App.vue # 根组件
├── main.js # 入口文件
├── env.d.ts # 环境声明
├── vite.config.ts # 构建配置
├── tsconfig.json # TypeScript 配置
├── package.json # 项目依赖
└── .eslintrc.js # ESLint 配置
使用 Vite 进行构建配置,确保开发和生产环境的高效性。
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 3000,
open: true,
},
build: {
target: 'es2020',
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
},
},
},
});
通过 composables 文件夹组织可复用逻辑。
// composables/useCounter.js
import { ref, computed } from 'vue';
export function useCounter() {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
return { count, doubleCount, increment };
}
<!-- 在组件中使用 -->
<script setup>
import { useCounter } from '@/composables/useCounter';
const { count, doubleCount, increment } = useCounter();
</script>
<template>
<div>
<h1>{{ count }}</h1>
<p>{{ doubleCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
使用 TypeScript 为 Composition API 提供类型支持。
// composables/useCounter.ts
import { ref, computed } from 'vue';
export interface CounterState {
count: number;
doubleCount: number;
}
export function useCounter(): CounterState {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
return { count, doubleCount: doubleCount.value, increment };
}
shallowReactive 和 shallowRef当不需要深层响应式处理时,使用 shallowReactive 和 shallowRef 以减少 Proxy 的嵌套代理。
import { shallowReactive } from 'vue';
const state = shallowReactive({
data: {
name: 'Vue 3',
description: 'A progressive JavaScript framework',
},
});
仅对需要响应式的数据使用 ref 和 reactive。
import { ref } from 'vue';
const name = ref('Vue 3');
const description = 'A progressive JavaScript framework';
将复杂组件拆分为多个小组件,提高可维护性和复用性。
<!-- ParentComponent.vue -->
<template>
<div>
<ChildComponent />
</div>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
</script>
<!-- ChildComponent.vue -->
<template>
<div>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
</template>
<script setup>
defineProps({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
});
</script>
使用 keep-alive 缓存不活动的组件实例。
<template>
<keep-alive include="TabComponent">
<component :is="currentComponent"></component>
</keep-alive>
</template>
<script setup>
import { ref } from 'vue';
import TabComponent from './TabComponent.vue';
const currentComponent = ref('TabComponent');
</script>
使用 defineAsyncComponent 实现组件的懒加载。
import { defineAsyncComponent } from 'vue';
const AsyncComponent = defineAsyncComponent(() => import('./AsyncComponent.vue'));
使用 Vue Devtools 和 Lighthouse 进行性能监控。
配置 Vue I18n 实现多语言支持。
// i18n.js
import { createI18n } from 'vue-i18n';
const i18n = createI18n({
legacy: false,
locale: 'en',
messages: {
en: {
greeting: 'Hello, Vue 3!',
},
zh: {
greeting: '你好,Vue 3!',
},
},
});
export default i18n;
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import i18n from './i18n';
const app = createApp(App);
app.use(i18n);
app.mount('#app');
在组件中动态切换语言。
<template>
<div>
<button @click="changeLanguage('en')">English</button>
<button @click="changeLanguage('zh')">中文</button>
<h1>{{ $t('greeting') }}</h1>
</div>
</template>
<script setup>
import { useI18n } from 'vue-i18n';
const { t, locale } = useI18n();
function changeLanguage(lang) {
locale.value = lang;
}
</script>
使用 Vue Router 的懒加载功能。
// router.js
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{
path: '/',
component: () => import('./views/HomeView.vue'),
},
{
path: '/about',
component: () => import('./views/AboutView.vue'),
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
使用路由守卫进行权限控制。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
Pinia 是 Vue 3 的官方状态管理库。
// store.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
},
});
<!-- 在组件中使用 -->
<script setup>
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
</script>
<template>
<div>
<h1>{{ counterStore.count }}</h1>
<button @click="counterStore.increment">Increment</button>
</div>
</template>
将状态管理拆分为多个模块。
// stores/modules/user.js
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
user: null,
}),
actions: {
setUser(user) {
this.user = user;
},
},
});
// stores/index.js
import { useUserStore } from './modules/user';
export { useUserStore };
Vitest 是 Vue 团队推荐的测试框架。
// counter.test.js
import { describe, it, expect } from 'vitest';
import { useCounter } from '@/composables/useCounter';
describe('useCounter', () => {
it('increments count', () => {
const { count, increment } = useCounter();
increment();
expect(count.value).toBe(1);
});
});
Cypress 是一个端到端测试框架。
// test/e2e/specs/homepage.spec.js
describe('Homepage', () => {
it('displays greeting', () => {
cy.visit('/');
cy.contains('Hello, Vue 3!').should('be.visible');
});
});
Vite 提供了快速的开发体验和高效的构建过程。
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
build: {
target: 'es2020',
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
},
},
},
});
将应用部署到生产环境。
npm run build
Vue Devtools 是 Vue 官方提供的浏览器扩展,用于调试 Vue 应用。
使用 ESLint 和 Prettier 确保代码风格一致。
// .eslintrc.js
module.exports = {
extends: ['plugin:vue/vue3-recommended', 'prettier'],
rules: {
'vue/multi-word-component-names': 'off',
},
};
实施代码审查流程,确保代码质量。
使用 Git Flow 管理项目分支。
# 创建功能分支
git checkout -b feature/new-component
# 提交更改
git add .
git commit -m 'Add new component'
# 合并到开发分支
git checkout develop
git merge feature/new-component
git branch -d feature/new-component
配置 GitHub Actions 实现自动化构建和部署。
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Install dependencies
run: npm install
- name: Build
run: npm run build
- name: Deploy
run: npm run deploy
使用 Netlify 部署静态网站。
# 安装 Netlify CLI
npm install -g netlify-cli
# 登录 Netlify
netlify login
# 部署
netlify deploy --prod
对用户输入进行验证,防止 XSS 攻击。
function validateInput(input) {
const regex = /^[a-zA-Z0-9\s]+$/;
return regex.test(input);
}
在 vite.config.ts 中配置 CSP。
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
middlewareMode: true,
},
build: {
target: 'es2020',
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
},
},
},
});
捕获全局错误并记录日志。
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import { createLogger } from './logger';
const app = createApp(App);
app.config.errorHandler = (err, vm, info) => {
createLogger().error(`Error in ${info}: ${err.message}`);
};
app.mount('#app');
使用 Winston 进行日志记录。
// logger.js
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console());
}
export function createLogger() {
return logger;
}
使用 ARIA 属性提升可访问性。
<template>
<button :aria-label="buttonLabel" @click="handleClick">
{{ buttonText }}
</button>
</template>
<script setup>
import { ref } from 'vue';
const buttonText = ref('Click me');
const buttonLabel = ref('Primary action button');
</script>
确保组件支持键盘导航。
<template>
<div role="tablist">
<div
v-for="(tab, index) in tabs"
:key="index"
role="tab"
:aria-selected="activeTab === index"
@click="activeTab = index"
@keydown.enter.space="activeTab = index"
tabindex="0"
>
{{ tab }}
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const tabs = ['Home', 'About', 'Contact'];
const activeTab = ref(0);
</script>
配置 PWA 支持。
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [
vue(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.ico', 'apple-touch-icon.png'],
manifest: {
name: 'My Vue 3 PWA',
short_name: 'My PWA',
description: 'A progressive web app built with Vue 3',
theme_color: '#ffffff',
icons: [
{
src: 'pwa-192x192.png',
sizes: '192x192',
type: 'image/png',
},
{
src: 'pwa-512x512.png',
sizes: '512x512',
type: 'image/png',
},
],
},
}),
],
});
使用 Workbox 配置离线支持。
// service-worker.js
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst } from 'workbox-strategies';
precacheAndRoute(self.__WB_MANIFEST);
registerRoute(
({ request }) => request.mode === 'navigate',
new CacheFirst({
cacheName: 'pages-cache',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
],
})
);
Nuxt 3 是 Vue 3 的官方框架,支持 SSR 和 SSG。
npm create nuxt-app@latest
// nuxt.config.ts
export default {
ssr: true,
target: 'static',
nitro: {
preset: 'vercel',
},
};
配置 Axios 进行 HTTP 请求。
// plugins/axios.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com',
});
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.provide('axios', api);
});
Vue Use 提供了许多实用的 Composition API。
// composables/useMouse.js
import { ref } from 'vue';
import { useMouse } from '@vueuse/core';
export function useMouse() {
const { x, y } = useMouse();
return { x, y };
}
<!-- 在组件中使用 -->
<script setup>
import { useMouse } from '@/composables/useMouse';
const { x, y } = useMouse();
</script>
<template>
<div>Mouse position: {{ x }},{{ y }}</div>
</template>
使用 Vue 的 <transition> 组件实现动画效果。
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition name="fade">
<div v-if="show">Hello, Vue 3!</div>
</transition>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
使用 CSS 动画库(如 Animate.css)增强动画效果。
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition name="bounce">
<div v-if="show">Hello, Vue 3!</div>
</transition>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
</script>
<style>
@import 'animate.css';
.bounce-enter-active {
animation: bounceIn 0.5s;
}
.bounce-leave-active {
animation: bounceOut 0.5s;
}
</style>
使用 Vue 的 <component> 标签实现动态组件。
<template>
<div>
<button @click="currentComponent = 'Home'">Home</button>
<button @click="currentComponent = 'About'">About</button>
<button @click="currentComponent = 'Contact'">Contact</button>
<component :is="currentComponent"></component>
</div>
</template>
<script setup>
import Home from './components/Home.vue';
import About from './components/About.vue';
import Contact from './components/Contact.vue';
const currentComponent = ref('Home');
</script>
开发自定义 Vue 插件。
// plugins/my-plugin.js
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.config.globalProperties.$myMethod = function () {
console.log('My plugin method');
};
});
<!-- 在组件中使用 -->
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
console.log(this.$myMethod());
});
</script>
配置 tsconfig.json 文件。
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
在组件中使用 TypeScript。
<script lang="ts" setup>
import { ref } from 'vue';
const count = ref(0);
const message = ref('Hello, Vue 3!');
const increment = () => {
count.value++;
};
</script>
<template>
<div>
<h1>{{ count }}</h1>
<p>{{ message }}</p>
<button @click="increment">Increment</button>
</div>
</template>
VitePress 是 Vue 团队提供的文档站点工具。
npm create vitepress@latest
在 docs 文件夹中编写文档。
# 项目文档
## 介绍
本项目是一个基于 Vue 3 的 Web 应用。
## 安装
```bash
npm install
npm run dev
npm run build
## 二十四、社区与资源利用
### (一)参与 Vue 社区
参与 Vue.js 社区,获取支持和分享经验。
### (二)利用官方资源
利用 Vue.js 官方文档和资源进行学习。
```bash
# 访问 Vue.js 官方文档
https://vuejs.org/
该电商网站因商品数据庞大且页面交互复杂,首屏加载耗时过长。通过升级至 Vue 3 并利用其新特性进行优化后,性能显著提升。
Suspense 组件异步加载商品列表与详情,搭配骨架屏提升用户体验。keep-alive 缓存商品分类与筛选组件,避免重复渲染。v-memo 指令缓存结果,减少重新渲染。该资讯类网站内容丰富且图片较多,移动端加载速度慢,用户流失严重。
# 安装 Vue 3 迁移构建工具
npm install @vue/vue3-migration-build
Vue 3 将继续发展,带来更多新特性和优化。
Vue 社区将持续壮大,提供更多优质的插件和工具。
Vue 3 将与 Web Components、WebAssembly 等新兴技术结合,拓展应用场景。
Vue 3 提供了多种内置优化和手动优化手段,包括响应式系统优化、编译优化、虚拟 DOM 优化、异步组件加载、代码分割、组件缓存等。通过合理利用这些策略,可以让应用性能更上一层楼,在大规模项目中提升用户体验和流畅度。希望开发者通过代码实践,深入理解这些特性的应用价值,并在项目中灵活运用。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online