--- name: advanced-patterns description: Vue 3 built-in components (Transition, Teleport, Suspense, KeepAlive) and advanced directives --- # Built-in Components & Directives ## Transition Animate enter/leave of a single element or component. ```vue ``` ### CSS Classes | Class | When | |-------|------| | `{name}-enter-from` | Start state for enter | | `{name}-enter-active` | Active state for enter (add transitions here) | | `{name}-enter-to` | End state for enter | | `{name}-leave-from` | Start state for leave | | `{name}-leave-active` | Active state for leave | | `{name}-leave-to` | End state for leave | ### Transition Modes ```vue ``` ### JavaScript Hooks ```vue
Content
``` ### Appear on Initial Render ```vue
Shows with animation on mount
``` ## TransitionGroup Animate list items. Each child must have a unique `key`. ```vue ``` ## Teleport Render content to a different DOM location. ```vue ``` ### Props ```vue ``` ## Suspense Handle async dependencies with loading states. **Experimental feature.** ```vue ``` ### Async Dependencies Suspense waits for: - Components with `async setup()` - Components using top-level `await` in ` ``` ### Events ```vue ... ``` ## KeepAlive Cache component instances when toggled. ```vue ``` ### Include/Exclude ```vue ``` ### Lifecycle Hooks ```ts import { onActivated, onDeactivated } from 'vue' onActivated(() => { // Called when component is inserted from cache fetchLatestData() }) onDeactivated(() => { // Called when component is removed to cache pauseTimers() }) ``` ## v-memo Skip re-renders when dependencies unchanged. Use for performance optimization. ```vue ``` Equivalent to `v-once` when empty: ```vue
Never updates
``` ## v-once Render once, skip all future updates. ```vue Static: {{ neverChanges }} ``` ## Custom Directives Create reusable DOM manipulations. ```ts // Directive definition const vFocus: Directive = { mounted: (el) => el.focus() } // Full hooks const vColor: Directive = { created(el, binding, vnode, prevVnode) {}, beforeMount(el, binding) {}, mounted(el, binding) { el.style.color = binding.value }, beforeUpdate(el, binding) {}, updated(el, binding) { el.style.color = binding.value }, beforeUnmount(el, binding) {}, unmounted(el, binding) {} } ``` ### Directive Arguments & Modifiers ```vue
``` ### Global Registration ```ts // main.ts app.directive('focus', { mounted: (el) => el.focus() }) ```