Performance
Optimize your Vue app for speed and efficiency. Use lazy loading, code splitting, and keep component trees shallow.
Performance is crucial for delivering a smooth user experience. Vue provides several strategies and features to help you build fast, efficient applications.
-
Use
v-showfor toggling visibility
v-showonly toggles the CSSdisplayproperty, making it more efficient thanv-ifwhen you need to frequently show/hide elements without destroying and recreating them.<template><div><button @click="visible = !visible">Toggle</button><p v-show="visible">This is conditionally visible.</p></div></template><script setup>import { ref } from "vue";const visible = ref(true);</script> -
Use async components
Load components only when needed to reduce initial bundle size. This is especially useful for large or rarely used components.// Async import in Vue Routerconst UserProfile = () => import("@/components/UserProfile.vue"); -
Avoid unnecessary reactivity
Only make data reactive when necessary. UseshallowRef,markRaw, orshallowReactivefor large objects or static data to avoid performance overhead.import { markRaw } from "vue";const staticData = markRaw(largeStaticObject); -
Use computed properties and watchers wisely
Computed properties are cached based on their dependencies. Avoid heavy computations inside computed properties or watchers. -
Keep component trees shallow
Deeply nested components can slow down rendering. Refactor large components and flatten the hierarchy where possible. -
Leverage code splitting
Use dynamic imports and Vue Router’s lazy loading to split your codebase and load only what’s needed. -
Optimize lists with
key
Always provide a uniquekeywhen rendering lists to help Vue track elements efficiently.<li v-for="item in items" :key="item.id">{{ item.name }}</li> -
Debounce expensive operations
For input handlers or API calls, use debouncing to limit the frequency of execution.import { debounce } from "lodash-es";const onInput = debounce((value) => {// handle input}, 300);