以下是针对 Vue3 项目代码优化的系统化方案,分为多个关键方向:
响应式优化
// 使用 shallowRef/shallowReactive 避免深层响应
const shallowData = shallowReactive({ largeObject: {} });
// 手动控制响应式范围
const nonReactiveData = markRaw({ staticData: [] });
渲染优化
<!-- 静态内容缓存 -->
<div v-once>{{ staticContent }}</div>
<!-- 列表项缓存 -->
<div v-for="item in list" :key="item.id" v-memo="[item.id]">
{{ item.content }}
</div>
计算属性优化
const expensiveValue = computed(() => {
// 添加计算结果缓存验证
return heavyCalculation(data.value);
});
组件拆分策略
// 动态组件加载
const AsyncComponent = defineAsyncComponent(() =>
import('./Component.vue').then(c => {
// 添加加载状态处理
return c;
})
);
逻辑复用模式
// Composition API 封装
export function usePagination(initialPage = 1) {
const page = ref(initialPage);
const nextPage = () => page.value++;
return { page, nextPage };
}
依赖管理
// 按需引入示例(Element Plus)
import { ElButton } from 'element-plus';
// Vite 配置自动按需导入
plugins: [Components({ resolvers: [ElementPlusResolver()] })]
代码分割策略
// 路由级代码分割
const routes = [{
path: '/dashboard',
component: () => import(/* webpackChunkName: "dashboard" */ './views/Dashboard.vue')
}];
构建配置优化
// vite.config.js 分包配置
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'vue-router'],
libs: ['lodash-es', 'axios']
}
}
}
}
事件监听管理
onMounted(() => {
const handler = () => { /* ... */ };
window.addEventListener('resize', handler);
onUnmounted(() => window.removeEventListener('resize', handler));
});
全局状态优化
// Pinia 状态管理优化
export const useStore = defineStore('main', {
state: () => ({ data: null }),
getters: {
filteredData: (state) => state.data?.filter(/* ... */)
}
});
代码质量保障
// ESLint 配置示例(.eslintrc.js)
rules: {
'vue/no-unused-components': 'error',
'vue/require-default-prop': 'warn'
}
模板规范
<!-- 优化前 -->
<div v-for="item in items" v-if="showItems">
<!-- 优化后 -->
<template v-for="item in filteredItems" :key="item.id">
<div>{{ item.name }}</div>
</template>
编译时优化
// 使用 @vue/compiler-sfc 预编译模板
// 配置 vue-loader 的 reactivityTransform: true
服务端渲染优化
// Nuxt3 配置示例
export default defineNuxtConfig({
ssr: true,
nitro: { preset: 'node-server' }
});
性能指标监控
// 使用 Navigation Timing API
const measurePerf = () => {
const [entry] = performance.getEntriesByType("navigation");
console.log('TTI:', entry.interactive);
};
内存分析
// 使用 Chrome DevTools Memory 面板
// 定期执行内存快照对比
建议通过 performance.mark()
API 建立性能标记点,结合 Chrome DevTools 的 Performance 面板进行细粒度分析。对于大型项目,建议实施渐进式优化策略,优先处理关键渲染路径(Critical Rendering Path)上的瓶颈点。