17.1 性能监控与诊断
17.1.1 核心性能指标
// 使用Performance API监控关键指标
function measurePerformance() {
// 首次内容绘制时间(FCP)
const fcp = performance.getEntriesByName('first-contentful-paint')[0].startTime
// 最大内容绘制时间(LCP)
const lcp = performance.getEntriesByName('largest-contentful-paint')[0]
// 交互响应时间
const interactionEntry = performance.getEntriesByType('event')[0]
console.table({
FCP: `${fcp.toFixed(2)}ms`,
LCP: `${lcp?.startTime.toFixed(2)}ms`,
InteractionDelay: `${interactionEntry.processingStart - interactionEntry.startTime}ms`
})
}
// 监听Vue生命周期进行分段测量
app.mixin({
mounted() {
if (this.$options.perfMark) {
performance.mark(`${this.$options.name}_mounted`)
}
}
})
17.1.2 Chrome DevTools高级用法
// 生成CPU分析文件
const cpuProfile = await navigator.device.cpu.requestProfile({
sampleInterval: 10,
duration: 5000
})
// 内存快照对比分析
function captureMemorySnapshot() {
window.performance.memory && console.log({
usedJSHeapSize: (window.performance.memory.usedJSHeapSize / 1024 / 1024).toFixed(2) + 'MB',
totalJSHeapSize: (window.performance.memory.totalJSHeapSize / 1024 / 1024).toFixed(2) + 'MB'
})
}
17.2 渲染性能优化
17.2.1 虚拟滚动实现
<template>
<div class="virtual-list" @scroll="handleScroll">
<div :style="scrollContentStyle">
<div v-for="item in visibleItems" :key="item.id">
<!-- 列表项内容 -->
</div>
</div>
</div>
</template>
<script>
export default {
props: ['items', 'itemSize'],
data: () => ({
startIndex: 0,
endIndex: 0
}),
computed: {
visibleItems() {
return this.items.slice(this.startIndex, this.endIndex)
},
scrollContentStyle() {
return {
height: `${this.items.length * this.itemSize}px`,
paddingTop: `${this.startIndex * this.itemSize}px`
}
}
},
methods: {
handleScroll(e) {
const scrollTop = e.target.scrollTop
this.startIndex = Math.floor(scrollTop / this.itemSize)
this.endIndex = Math.min(
this.startIndex + Math.ceil(e.target.clientHeight / this.itemSize),
this.items.length
)
}
}
}
</script>
17.2.2 响应式数据优化
// 冻结大数组避免响应式转换
const heavyData = Object.freeze(
Array.from({ length: 10000 }, (_, i) => ({ id: i, value: Math.random() }))
)
// 使用shallowRef优化对象性能
const largeObject = shallowRef({
/* 大型嵌套对象 */
})
// 按需更新的自定义Ref
function optimizedRef<T>(value: T) {
const track = useTrack()
const trigger = useTrigger()
return customRef((track, trigger) => ({
get() {
track()
return value
},
set(newValue) {
if (deepEqual(value, newValue)) return
value = newValue
trigger()
}
}))
}
17.3 构建优化策略
17.3.1 依赖分析配置
// vite.config.js
import { visualizer } from 'rollup-plugin-visualizer'
export default {
plugins: [
visualizer({
open: true,
gzipSize: true,
brotliSize: true
})
]
}
// 生成分析报告后的优化决策示例:
// 1. 按需加载ECharts:import { BarChart } from 'echarts/charts'
// 2. 移除moment locales:new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
17.3.2 代码分割策略
// 路由级动态导入
const routes = [
{
path: '/dashboard',
component: () => import(/* webpackChunkName: "dashboard" */ './views/Dashboard.vue')
}
]
// 组件级动态导入
const HeavyComponent = defineAsyncComponent({
loader: () => import('./HeavyComponent.vue'),
loadingComponent: LoadingSpinner,
delay: 200,
timeout: 3000
})
17.4 运行时优化技巧
17.4.1 事件处理优化
<template>
<!-- 防抖处理高频事件 -->
<input @input="debouncedSearch" />
<!-- 被动事件提升滚动性能 -->
<div @wheel.passive="handleScroll"></div>
</template>
<script>
import { debounce } from 'lodash-es'
export default {
methods: {
debouncedSearch: debounce(function() {
// 搜索逻辑
}, 300)
}
}
</script>
17.4.2 计算属性缓存
const heavyComputation = computed(() => {
// 使用WeakMap缓存结果
const cache = new WeakMap()
return (data: object) => {
if (cache.has(data)) return cache.get(data)
const result = /* 复杂计算 */
cache.set(data, result)
return result
}
})
17.5 高级性能模式
17.5.1 Web Worker集成
// worker-wrapper.js
export function runInWorker(fn) {
const workerCode = `(${fn.toString()})()`
const blob = new Blob([workerCode], { type: 'application/javascript' })
return new Worker(URL.createObjectURL(blob))
}
// 在组件中使用
const worker = runInWorker(() => {
self.onmessage = ({ data }) => {
const result = heavyTask(data)
self.postMessage(result)
}
})
worker.postMessage(inputData)
worker.onmessage = ({ data }) => {
// 处理结果
}
17.5.2 WASM加速示例
<template>
<button @click="runWasmTask">执行计算</button>
</template>
<script>
import init, { complex_calculation } from './wasm/pkg'
export default {
async mounted() {
await init()
},
methods: {
runWasmTask() {
const result = complex_calculation(/* 参数 */)
// 处理结果
}
}
}
</script>
本章重点总结:
- 监控先行:建立性能基线,量化优化效果
- 渲染优化:虚拟滚动与响应式数据精细化控制
- 构建提效:代码分割与依赖分析双管齐下
- 运行优化:高频操作与计算密集型任务特殊处理
- 前沿方案:Web Worker与WASM突破性能瓶颈
性能优化检查清单:
- 首屏关键资源预加载
- 未使用的CSS/JS移除
- 图片资源懒加载+WebP格式
- 第三方库按需引入
- 合理使用浏览器缓存策略
- 开启Gzip/Brotli压缩
- 服务端开启HTTP/2
- 关键路由预渲染
- 长任务分解(<50ms)
// 性能监控集成示例(Sentry)
import * as Sentry from '@sentry/vue'
Sentry.init({
app,
dsn: 'your-dsn',
integrations: [new Sentry.BrowserTracing()],
tracesSampleRate: 0.2,
beforeSend(event) {
// 添加性能指标到监控事件
event.measurements = {
fcp: { value: getFCP() },
lcp: { value: getLCP() }
}
return event
}
})