一个卡顿的看板页面
监控大屏需要同时渲染 8000 个数据点。用 Vue 2 时代那套写法,加载时主线程直接阻塞 4 秒,交互全卡死。
原因很快定位到:Vue 3 的 reactive 会深度递归劫持对象每一个层级。8000 个点、每个点 12 个字段,Proxy 对象数量爆炸。
// 问题代码
const raw = await fetch('/api/metrics').then(r => r.json());
const state = reactive(raw); // 创建了近 10 万个 Proxy
响应式原理与三种声明式 API
Vue 3 用 Proxy 替代了 Vue 2 的 Object.defineProperty。reactive 返回的是 Proxy,拦截 get/set/deleteProperty 等操作。
三种 API 的适用场景完全不同:
| API | 追踪深度 | 返回值 | 适用场景 |
|---|---|---|---|
reactive(obj) | 深层 | Proxy 对象 | 稳定的表单模型、配置对象 |
ref(value) | 依赖 .value 的访问 | .value | 单值状态、可替换整个对象 |
shallowRef(value) | 仅顶层 | .value | 大数组、大对象、第三方实例 |
shallowRef:解开深度劫持
<script setup>
import { shallowRef, triggerRef } from 'vue'
const chartData = shallowRef(null)
async function loadData() {
chartData.value = await fetch('/api/metrics').then(r => r.json())
// 只触发一次依赖更新
triggerRef(chartData)
}
function updatePoint(index, value) {
// 手动改内部数据,不触发响应式
chartData.value.series[index].value = value
triggerRef(chartData) // 手动通知
}
</script>
<template>
<EChart v-if="chartData" :data="chartData" />
</template>
对比效果:8000 点位从 4.2s 降到 340ms。
markRaw:标记不需要代理的对象
如果某些第三方实例(图表实例、地图实例、Worker)挂在响应式对象上,Vue 会尝试代理它们,通常会报错或严重拖慢:
import { markRaw } from 'vue'
const echartsRegistry = new Map()
function getChartInstance(dom) {
if (!echartsRegistry.has(dom)) {
// markRaw 告诉 Vue 跳过这个对象
const instance = echarts.init(dom)
echartsRegistry.set(dom, markRaw(instance))
}
return echartsRegistry.get(dom)
}
同理适用于 Date、RegExp、DOM 节点、第三方 SDK 实例。
toRef vs toRefs
const state = reactive({ count: 1, name: 'foo' })
// 解构会丢失响应性
const { count, name } = state // ❌ 变成普通值
// toRefs 保持引用
const countRef = toRef(state, 'count') // 单个
const { count, name } = toRefs(state) // 批量(注意返回的是 ref)
在 <script setup> 里,配合 reactive 用 toRefs 解构;配合 ref 则直接解构 .value。
computed 与 watch 的取舍
// ❌ watch 手动管理依赖,容易漏
const total = ref(0)
watch(items, (val) => {
total.value = val.reduce((s, i) => s + i.price * i.count, 0)
})
// ✅ computed 缓存,只在依赖变化时重算
const total = computed(() =>
items.value.reduce((s, i) => s + i.price * i.count, 0)
)
computed 是惰性 + 缓存的:没有组件读取它的值,就永远不会计算。多次读取也只算一次。
需要副作用时才用 watch,且务必注意:
// ❌ 深度监听大数组,每次深比较都很贵
watch(form, (nv, ov) => { save(nv) }, { deep: true })
// ✅ 监听具体字段
watch(() => form.status, (nv) => { saveField('status', nv) })
// ✅ 大数组用 flush: 'post',等 DOM 更新完再执行
watch(list, async () => {
await nextTick()
measureHeight()
}, { flush: 'post' })
flush 三个选项的区别:
| 值 | 执行时机 |
|---|---|
pre | 组件更新前(默认) |
post | DOM 更新完成后 |
sync | 同步,修改即触发(慎用,易递归) |
万行表格:虚拟滚动
原生 <table> 渲染 5000 行会生成 5000 个 DOM 节点,浏览器直接卡死。虚拟滚动的思路是:只渲染可视区域 ± 缓冲区的数据。
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
const props = defineProps({
rows: { type: Array, required: true },
rowHeight: { type: Number, default: 44 },
height: { type: Number, default: 600 },
overscan: { type: Number, default: 5 }
})
const containerRef = ref(null)
const scrollTop = ref(0)
const visibleRange = computed(() => {
const start = Math.floor(scrollTop.value / props.rowHeight) - props.overscan
const visibleCount = Math.ceil(props.height / props.rowHeight) + props.overscan * 2
return {
start: Math.max(0, start),
end: Math.min(props.rows.length, start + visibleCount)
}
})
const visibleRows = computed(() =>
props.rows.slice(visibleRange.value.start, visibleRange.value.end)
)
// 占位块撑开滚动条总高度
const topPadding = computed(() => visibleRange.value.start * props.rowHeight)
const bottomPadding = computed(
() => (props.rows.length - visibleRange.value.end) * props.rowHeight
)
function onScroll(e) {
scrollTop.value = e.target.scrollTop
}
</script>
<template>
<div ref="containerRef" class="virtual-table" :style="{ height: `${height}px` }"
@scroll.passive="onScroll">
<table>
<thead>
<tr><th>ID</th><th>名称</th><th>状态</th></tr>
</thead>
<tbody>
<tr :style="{ height: `${topPadding}px` }" aria-hidden="true">
<td colspan="3"></td>
</tr>
<tr v-for="row in visibleRows" :key="row.id" :style="{ height: `${rowHeight}px` }">
<td>{{ row.id }}</td>
<td>{{ row.name }}</td>
<td>{{ row.status }}</td>
</tr>
<tr :style="{ height: `${bottomPadding}px` }" aria-hidden="true">
<td colspan="3"></td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.virtual-table { overflow-y: auto; will-change: scroll-position; }
</style>
要点:
@scroll.passive避免阻塞滚动- 行高必须固定,否则无法计算偏移
- 上下占位
tr撑开滚动条
实测 5000 行渲染耗时从 3.8s → 46ms。
现成方案:vue-virtual-scroller(支持不定行高)、vueuse 的 useVirtualList。
首屏体积优化
以一个后台管理页面为例,构建产物优化前后:
| 阶段 | 体积(gzip) | 首屏时间 |
|---|---|---|
| 原始 | 1.42 MB | 4.1s |
| 路由懒加载后 | 612 KB | 2.3s |
| + Element Plus 按需引入 | 358 KB | 1.6s |
| + Gzip/Brotli | 214 KB | 1.1s |
路由懒加载
// ❌ 全部打进首屏
import UserList from './views/UserList.vue'
import OrderDetail from './views/OrderDetail.vue'
// ✅ 按需加载
const routes = [
{
path: '/users',
component: () => import(/* webpackChunkName: "users" */ './views/UserList.vue')
}
]
组件按需引入
Element Plus 这类 UI 库全量引入会拖慢构建和运行:
// vite.config.js
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
Components({ resolvers: [ElementPlusResolver()] }) // 自动按需
],
build: {
rollupOptions: {
output: {
manualChunks: {
vue: ['vue', 'vue-router', 'pinia'],
echarts: ['echarts', 'echarts/core'],
utils: ['lodash-es', 'dayjs']
}
}
}
}
})
长列表 key 的选择
<!-- ❌ 用 index:顺序变化时状态错位 -->
<li v-for="(item, i) in list" :key="i">{{ item.name }}</li>
<!-- ✅ 用稳定唯一 id -->
<li v-for="item in list" :key="item.id">{{ item.name }}</li>
用 index 作 key 时,如果列表头部插入了一条,所有后续组件的 DOM 复用关系会错乱——表现为输入框内容串位、动画错乱。
nextTick 与 DOM 操作时机
// ❌ DOM 还没更新就读高度
this.$nextTick(() => {}) // Options API
// ✅ 组合式 API 正确写法
import { nextTick } from 'vue'
async function focusInput() {
showInput.value = true
await nextTick()
inputRef.value?.focus()
}
性能检测工具
// 1. Performance API:看长任务
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach(e => {
if (e.duration > 50) {
console.warn('长任务', e.name, e.duration, 'ms', e.attribution)
}
})
})
observer.observe({ entryTypes: ['longtask'] })
// 2. Vue Devtools 组件树耗时
// 3. Chrome Performance 面板录制,看火焰图找长函数
// 4. 路由懒加载分包大小检查
console.table(performance.getEntriesByType('resource')
.filter(r => r.name.endsWith('.js'))
.map(r => ({ name: r.name.split('/').pop(), size: r.transferSize / 1024 })))
优化清单
- 大对象用
shallowRef,配合triggerRef手动触发 - 第三方实例必须
markRaw - 优先
computed,慎用deep: true - 超过 500 行的列表上虚拟滚动
- 路由懒加载 + UI 库按需引入
v-for用稳定 id 作 keynextTick等 DOM 更新完成再操作- 用
passive事件监听器处理高频滚动
下一篇写 Docker 部署与 CI,把静态博客的发布流程自动化。