第19篇:性能优化策略与实践

发布于:2025-02-24 ⋅ 阅读:(13) ⋅ 点赞:(0)

目标:掌握 Vue3 性能优化的核心方法与实战技巧


1. 性能分析工具
  1. Chrome DevTools - Performance
    • 录制运行时性能
    • 分析长任务(Long Tasks)和内存泄漏
  2. Vue DevTools - Performance
    • 组件渲染耗时分析
    • 时间线跟踪
  3. Lighthouse
    • 生成性能评分报告
    • 识别阻塞资源、未压缩文件等问题

2. 代码体积优化
  1. Tree Shaking(Vite默认支持)
    // 按需引入组件库  
    import { Button } from 'ant-design-vue'  
    
  2. 代码分割(动态导入)
    const HeavyComponent = defineAsyncComponent(() =>  
      import('./HeavyComponent.vue')  
    )  
    
  3. Gzip/Brotli压缩
    # vite.config.js 配置  
    import viteCompression from 'vite-plugin-compression'  
    plugins: [viteCompression({ algorithm: 'brotliCompress' })]  
    

3. 渲染优化
  1. v-for 优化
    <template>  
      <!-- 始终指定唯一key -->  
      <div v-for="item in list" :key="item.id">{{ item.name }}</div>  
    
      <!-- 虚拟滚动处理长列表 -->  
      <VirtualList :items="bigData" :item-size="50" />  
    </template>  
    
  2. 减少响应式依赖
    // 冻结不需要响应式的大对象  
    const staticData = Object.freeze(largeData)  
    
  3. 组件懒加载
    // 路由配置  
    {  
      path: '/dashboard',  
      component: () => import('@/views/Dashboard.vue')  
    }  
    

4. 运行时优化
  1. 防抖/节流
    <script setup>  
    import { debounce } from 'lodash-es'  
    const search = debounce(() => {  
      // 搜索逻辑  
    }, 300)  
    </script>  
    
  2. 计算属性缓存
    const filteredList = computed(() =>  
      bigData.value.filter(item => item.active)  
    )  
    
  3. v-once/v-memo
    <template>  
      <!-- 静态内容 -->  
      <footer v-once>© 2024 公司名称</footer>  
    
      <!-- 按条件缓存 -->  
      <div v-memo="[user.id]">{{ user.name }}</div>  
    </template>  
    

5. 第三方库优化
  1. CDN引入
    <!-- index.html -->  
    <script src="https://unpkg.com/lodash@4.17.21/lodash.min.js"></script>  
    
    // vite.config.js  
    externals: {  
      'lodash': '_'  
    }  
    
  2. 按需加载图标库
    // 使用 unplugin-icons 自动按需加载  
    import IconAccessibility from '~icons/carbon/accessibility'  
    

6. 内存管理
  1. 定时器清理
    onUnmounted(() => {  
      clearInterval(timer)  
      window.removeEventListener('resize', handler)  
    })  
    
  2. 大对象释放
    const heavyData = ref(null)  
    onBeforeUnmount(() => {  
      heavyData.value = null // 主动释放内存  
    })  
    

优化前后对比示例

场景 优化前 优化后
首页加载体积 2.5MB 850KB(Gzip后)
列表渲染1000条数据 1200ms 200ms(虚拟滚动)
频繁搜索请求 10请求/秒 2请求/秒(防抖)

性能优化原则

  1. 测量优先:优化前先用工具定位瓶颈
  2. 渐进增强:优先解决主要性能问题
  3. 用户体验优先:关注FCP(首次内容渲染)、TTI(可交互时间)