以下是使用 Vue 3 Composition API 优化项目的通俗指南,无需复杂术语,直接上干货:
1. 像搭积木一样复用逻辑
- 问题:多个组件有重复逻辑(比如获取数据、计时器),复制粘贴代码很麻烦。
- 解决:用
Composables
(自定义函数)封装逻辑,随用随取。
使用:// useTimer.js import { ref, onUnmounted } from 'vue';export function useTimer() {const seconds = ref(0);let timer = null;const start = () => {timer = setInterval(() => {seconds.value++;}, 1000);};// 自动清理定时器(避免内存泄漏)onUnmounted(() => clearInterval(timer));return { seconds, start }; }
// 组件内 import { useTimer } from './useTimer'; const { seconds, start } = useTimer(); start(); // 直接调用
2. 响应式数据:该省则省
- 问题:所有数据都加响应式,性能浪费。
- 技巧:
- 基本类型用
ref
:const count = ref(0)
- 对象/数组用
reactive
:const user = reactive({ name: '张三' })
- 不需要响应式的数据:用普通变量或
readonly
。const staticConfig = { api: '/data' }; // 不响应 const frozenData = readonly(user); // 禁止修改
- 基本类型用
3. 性能优化:少干活,多偷懒
-
列表渲染:
- 加
key
:<div v-for="item in list" :key="item.id">
- 万级数据用虚拟滚动(比如只渲染看得见的 20 条)。
- 加
-
条件渲染:
- 频繁切换用
v-show
(不销毁元素):<div v-show="isVisible">
- 一次性渲染用
v-if
(减少初始负载)。
- 频繁切换用
-
计算属性缓存:
const fullName = computed(() => `${firstName} ${lastName}`); // 自动缓存结果
4. 代码组织:让 setup 干净清爽
-
拆分逻辑块:把不同功能写在独立的
Composables
里。setup() {// 数据获取const { data, error } = useFetch('/api/data');// 用户交互const { position, trackClick } = useMouseTracker();// 定时器const { seconds } = useTimer();return { data, error, position, seconds }; }
-
生命周期钩子:在
setup
里直接调用:onMounted(() => console.log('组件加载了!')); onUnmounted(() => clearTimeout(timer)); // 销毁时清理
5. 实战场景:表单提交优化
- 问题:表单提交时,重复处理加载状态、错误提示。
- 优化:封装一个
useFormSubmit
:
使用:// useFormSubmit.js import { ref } from 'vue';export function useFormSubmit(apiFn) {const isLoading = ref(false);const error = ref(null);const submit = async (formData) => {isLoading.value = true;try {await apiFn(formData); // 传入具体的提交函数error.value = null;} catch (err) {error.value = err.message;} finally {isLoading.value = false;}};return { isLoading, error, submit }; }
const { isLoading, error, submit } = useFormSubmit((data) => {return axios.post('/api/submit', data); // 传入提交逻辑 });
总结
- 复用逻辑:用
Composables
代替 Mixins,像乐高一样拼装代码。 - 数据精准响应:别给不需要变化的数据加响应式。
- 性能偷懒:少渲染、少计算、少监听。
- 代码整洁:一个函数只干一件事,拆分成小块。