Vue3 性能优化实战技巧全整理

发布于2026-08-21 14:49 阅读13次 系统整理 Vue3 项目性能优化的实战技巧,涵盖响应式优化(shallowRef/markRaw)、组件懒加载、虚拟列表、v-memo、KeepAlive、打包优化等方面,附代码示例和适用场景分析,帮助提升应用性能。
# Vue3 性能优化实战技巧全整理
## 前言
Vue3 本身性能已经很好,但项目规模一大、数据量一多,还是会出现卡顿。本文从响应式、渲染、加载、打包四个维度整理常用优化技巧,都是实战中验证过有效的。
## 一、响应式优化
### 1. shallowRef / shallowReactive
对于大对象或只改顶层引用的场景,用浅层响应式避免深层代理的开销。
```javascript
import { shallowRef, shallowReactive } from "vue";
// 大对象用 shallowRef,只追踪 .value 的替换
const bigData = shallowRef({ list: [] });
bigData.value = newData; // 触发更新
// 浅层响应式,只追踪第一层属性
const config = shallowReactive({ theme: "dark", settings: {} });
```
### 2. markRaw 标记非响应式对象
```javascript
import { markRaw } from "vue";
// 第三方库实例、大数组,不需要响应式
const echartsInstance = markRaw(echarts.init(dom));
const chartData = reactive({
instance: echartsInstance, // 不会被代理
});
```
## 二、渲染优化
### 3. v-memo 缓存子树
```html
<div v-for="item in list" :key="item.id" v-memo="[item.id, item.selected]">
<!-- 只有 id 或 selected 变化才重新渲染 -->
<ExpensiveComponent :item="item" />
</div>
```
### 4. v-once 静态内容
```html
<div v-once>
<!-- 只渲染一次,之后不再更新 -->
{{ staticContent }}
</div>
```
### 5. 列表用 key 和稳定组件
```html
<!-- 稳定的 key 让 Vue 复用节点 -->
<li v-for="item in list" :key="item.id">{{ item.name }}</li>
```
## 三、大列表优化
### 6. 虚拟列表
几千上万条数据不要全量渲染,用虚拟列表只渲染可视区。
```javascript
import { RecycleScroller } from "vue-virtual-scroller";
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
// 模板
<RecycleScroller
class="scroller"
:items="items"
:item-size="60"
key-field="id"
v-slot="{ item }">
<RowItem :item="item" />
</RecycleScroller>
```
### 7. 分页 / 懒加载
```javascript
// 滚动到底部加载更多
const loadMore = () => {
if (page.value * pageSize < total.value) {
page.value++;
fetchData();
}
};
```
## 四、组件懒加载
### 8. 异步组件按需加载
```javascript
// 路由级懒加载
const routes = [
{
path: "/dashboard",
component: () => import("./views/Dashboard.vue"),
},
];
// 组件级懒加载
const HeavyComponent = defineAsyncComponent(() =>
import("./components/HeavyComponent.vue")
);
```
### 9. KeepAlive 缓存组件
```html
<KeepAlive :max="10">
<component :is="currentComponent" />
</KeepAlive>
```
缓存切换频繁的组件,避免重复创建销毁。
## 五、打包优化
### 10. 分包与按需引入
```javascript
// vite.config.js
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ["vue", "vue-router", "pinia"],
echarts: ["echarts"],
},
},
},
},
};
```
### 11. 压缩与 CDN
```javascript
// 第三方库走 CDN,减小包体积
// vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
build: {
rollupOptions: {
external: ["vue", "echarts"],
},
},
});
```
## 性能检查清单
- [ ] 大对象用 shallowRef
- [ ] 第三方实例 markRaw
- [ ] 大列表用虚拟列表
- [ ] 路由组件懒加载
- [ ] 高频切换组件 KeepAlive
- [ ] 第三方库按需引入或 CDN
## 小结
性能优化的核心是"减少不必要的响应式代理和渲染"。优先处理大列表和重型组件,这两个是最常见的卡顿来源。用 Vue Devtools 的 Performance 面板定位慢组件,再针对性优化。