Vue3 使用小技巧
-
1.v-memo 渲染 :大型列表更新时全量重渲染卡顿技巧:仅当依赖项变化时更新DOM
<template> <!-- 仅当item.id或item.data变化时重渲染 --> <div v-for="item in list" :key="item.id" v-memo="[item.id, item.data]"> {{ heavyCompute(item) }} <!-- 昂贵计算 --> </div> </template>2.Reactivity Transform 解构
痛点:.value地狱污染代码
技巧:编译器自动解构ref<script setup> let count = $ref(0) // 直接使用count而非count.value const double = $computed(() => count * 2) // 自动解构 </script>3.动态组件工厂模式
痛点:冗余的<component :is>逻辑
技巧:JSX实现组件工厂const componentFactory = (type) => defineComponent({ setup: () => () => h(resolveComponent(`${type}-component`)) }) // 使用:<component :is="componentFactory('chart')" />4.依赖注入的防污染技
痛点:provide/inject命名冲突
技巧:Symbol作为注入密钥// auth.js export const AuthKey = Symbol() // 父级 provide(AuthKey, { user: ref(null) }) // 子级 const auth = inject(AuthKey) // 完全隔离5.Effect Scope 精准内存回收
痛点:手动清理computed/watch易遗漏
技巧:作用域自动回收import { effectScope } from 'vue' const scope = effectScope() scope.run(() => { const doubled = computed(() => count.value * 2) watch(count, (v) => console.log(v)) }) scope.stop() // 一键清理所有