chore: init monorepo with existing website and plans

This commit is contained in:
yeuimu
2026-06-15 02:31:15 +08:00
commit 72bc89ab03
488 changed files with 115304 additions and 0 deletions
+202
View File
@@ -0,0 +1,202 @@
---
name: vue-debug-guides
description: Vue 3 debugging and error handling for runtime errors, warnings, async failures, and SSR/hydration issues. Use when diagnosing or fixing Vue issues.
---
Vue 3 debugging and error handling for runtime issues, warnings, async failures, and hydration bugs.
For development best practices and common gotchas, use `vue-best-practices`.
### Reactivity
- Tracing unexpected re-renders and state updates → See [reactivity-debugging-hooks](reference/reactivity-debugging-hooks.md)
- Ref values not updating due to missing .value access → See [ref-value-access](reference/ref-value-access.md)
- State stops updating after destructuring reactive objects → See [reactive-destructuring](reference/reactive-destructuring.md)
- Refs inside arrays, Maps, or Sets not unwrapping → See [refs-in-collections-need-value](reference/refs-in-collections-need-value.md)
- Nested refs rendering as [object Object] in templates → See [template-ref-unwrapping-top-level](reference/template-ref-unwrapping-top-level.md)
- Reactive proxy identity comparisons always return false → See [reactivity-proxy-identity-hazard](reference/reactivity-proxy-identity-hazard.md)
- Third-party instances breaking when proxied → See [reactivity-markraw-for-non-reactive](reference/reactivity-markraw-for-non-reactive.md)
- Watchers only firing once per tick unexpectedly → See [reactivity-same-tick-batching](reference/reactivity-same-tick-batching.md)
### Computed
- Computed getter triggers mutations or requests unexpectedly → See [computed-no-side-effects](reference/computed-no-side-effects.md)
- Mutating computed values causes changes to disappear → See [computed-return-value-readonly](reference/computed-return-value-readonly.md)
- Computed value never updates after conditional logic → See [computed-conditional-dependencies](reference/computed-conditional-dependencies.md)
- Sorting or reversing arrays breaks original state → See [computed-array-mutation](reference/computed-array-mutation.md)
- Passing parameters to computed properties fails → See [computed-no-parameters](reference/computed-no-parameters.md)
### Watchers
- Async operations overwriting with stale data → See [watch-async-cleanup](reference/watch-async-cleanup.md)
- Creating watchers inside async callbacks → See [watch-async-creation-memory-leak](reference/watch-async-creation-memory-leak.md)
- Watcher never triggers for reactive object properties → See [watch-reactive-property-getter](reference/watch-reactive-property-getter.md)
- Async watchEffect misses dependencies after await → See [watcheffect-async-dependency-tracking](reference/watcheffect-async-dependency-tracking.md)
- DOM reads are stale inside watcher callbacks → See [watch-flush-timing](reference/watch-flush-timing.md)
- Deep watchers report identical old/new values → See [watch-deep-same-object-reference](reference/watch-deep-same-object-reference.md)
- watchEffect runs before template refs update → See [watcheffect-flush-post-for-refs](reference/watcheffect-flush-post-for-refs.md)
### Components
- Child component throws "component not found" error → See [local-components-not-in-descendants](reference/local-components-not-in-descendants.md)
- Click listener doesn't fire on custom component → See [click-events-on-components](reference/click-events-on-components.md)
- Parent can't access child ref data in script setup → See [component-ref-requires-defineexpose](reference/component-ref-requires-defineexpose.md)
- HTML template parsing breaks Vue component syntax → See [in-dom-template-parsing-caveats](reference/in-dom-template-parsing-caveats.md)
- Wrong component renders due to naming collisions → See [component-naming-conflicts](reference/component-naming-conflicts.md)
- Parent styles don't apply to multi-root component → See [multi-root-component-class-attrs](reference/multi-root-component-class-attrs.md)
### Props & Emits
- Variables referenced in defineProps cause errors → See [prop-defineprops-scope-limitation](reference/prop-defineprops-scope-limitation.md)
- Component emits undeclared event causing warnings → See [declare-emits-for-documentation](reference/declare-emits-for-documentation.md)
- defineEmits used inside function or conditional → See [defineEmits-must-be-top-level](reference/defineEmits-must-be-top-level.md)
- defineEmits has both type and runtime arguments → See [defineEmits-no-runtime-and-type-mixed](reference/defineEmits-no-runtime-and-type-mixed.md)
- Native event listeners not responding to clicks → See [native-event-collision-with-emits](reference/native-event-collision-with-emits.md)
- Component event fires twice when clicking → See [undeclared-emits-double-firing](reference/undeclared-emits-double-firing.md)
### Templates
- Getting template compilation errors with statements → See [template-expressions-restrictions](reference/template-expressions-restrictions.md)
- "Cannot read property of undefined" runtime errors → See [v-if-null-check-order](reference/v-if-null-check-order.md)
- Dynamic directive arguments not working properly → See [dynamic-argument-constraints](reference/dynamic-argument-constraints.md)
- v-else elements rendering unconditionally always → See [v-else-must-follow-v-if](reference/v-else-must-follow-v-if.md)
- Mixing v-if with v-for causes precedence bugs and migration breakage → See [no-v-if-with-v-for](reference/no-v-if-with-v-for.md)
- Template function calls mutating state cause unpredictable re-render bugs → See [template-functions-no-side-effects](reference/template-functions-no-side-effects.md)
- Child components in loops showing undefined data → See [v-for-component-props](reference/v-for-component-props.md)
- Array order changing after sorting or reversing → See [v-for-computed-reverse-sort](reference/v-for-computed-reverse-sort.md)
- List items disappearing or swapping state unexpectedly → See [v-for-key-attribute](reference/v-for-key-attribute.md)
- Getting off-by-one errors with range iteration → See [v-for-range-starts-at-one](reference/v-for-range-starts-at-one.md)
- v-show or v-else not working on template elements → See [v-show-template-limitation](reference/v-show-template-limitation.md)
### Template Refs
- Ref becomes null when element is conditionally hidden → See [template-ref-null-with-v-if](reference/template-ref-null-with-v-if.md)
- Ref array indices don't match data array in loops → See [template-ref-v-for-order](reference/template-ref-v-for-order.md)
- Refactoring template ref names breaks silently in code → See [use-template-ref-vue35](reference/use-template-ref-vue35.md)
### Forms & v-model
- Initial form values not showing when using v-model → See [v-model-ignores-html-attributes](reference/v-model-ignores-html-attributes.md)
- Textarea content changes not updating the ref → See [textarea-no-interpolation](reference/textarea-no-interpolation.md)
- iOS users cannot select dropdown first option → See [select-initial-value-ios-bug](reference/select-initial-value-ios-bug.md)
- Parent and child components have different values → See [define-model-default-value-sync](reference/define-model-default-value-sync.md)
- Object property changes not syncing to parent → See [definemodel-object-mutation-no-emit](reference/definemodel-object-mutation-no-emit.md)
- Real-time search/validation broken for Chinese/Japanese input → See [v-model-ime-composition](reference/v-model-ime-composition.md)
- Number input returns empty string instead of zero → See [v-model-number-modifier-behavior](reference/v-model-number-modifier-behavior.md)
- Custom checkbox values not submitted in forms → See [checkbox-true-false-value-form-submission](reference/checkbox-true-false-value-form-submission.md)
### Events & Modifiers
- Chaining multiple event modifiers produces unexpected results → See [event-modifier-order-matters](reference/event-modifier-order-matters.md)
- Keyboard shortcuts don't fire with system modifier keys → See [keyup-modifier-timing](reference/keyup-modifier-timing.md)
- Keyboard shortcuts fire with unintended modifier combinations → See [exact-modifier-for-precise-shortcuts](reference/exact-modifier-for-precise-shortcuts.md)
- Combining passive and prevent modifiers breaks event behavior → See [no-passive-with-prevent](reference/no-passive-with-prevent.md)
### Lifecycle
- Memory leaks from unremoved event listeners → See [cleanup-side-effects](reference/cleanup-side-effects.md)
- DOM access fails before component mounts → See [lifecycle-dom-access-timing](reference/lifecycle-dom-access-timing.md)
- DOM reads return stale values after state changes → See [dom-update-timing-nexttick](reference/dom-update-timing-nexttick.md)
- SSR rendering differs from client hydration → See [lifecycle-ssr-awareness](reference/lifecycle-ssr-awareness.md)
- Lifecycle hooks registered asynchronously never run → See [lifecycle-hooks-synchronous-registration](reference/lifecycle-hooks-synchronous-registration.md)
### Slots
- Accessing child component data in slot content returns undefined values → See [slot-render-scope-parent-only](reference/slot-render-scope-parent-only.md)
- Mixing named and scoped slots together causes compilation errors → See [slot-named-scoped-explicit-default](reference/slot-named-scoped-explicit-default.md)
- Using v-slot on native HTML elements causes compilation errors → See [slot-v-slot-on-components-or-templates-only](reference/slot-v-slot-on-components-or-templates-only.md)
- Unexpected content placement from implicit default slot behavior → See [slot-implicit-default-content](reference/slot-implicit-default-content.md)
- Scoped slot props missing expected name property → See [slot-name-reserved-prop](reference/slot-name-reserved-prop.md)
- Wrapper components breaking child slot functionality → See [slot-forwarding-to-child-components](reference/slot-forwarding-to-child-components.md)
### Provide/Inject
- Calling provide after async operations fails silently → See [provide-inject-synchronous-setup](reference/provide-inject-synchronous-setup.md)
- Tracing where provided values come from → See [provide-inject-debugging-challenges](reference/provide-inject-debugging-challenges.md)
- Injected values not updating when provider changes → See [provide-inject-reactivity-not-automatic](reference/provide-inject-reactivity-not-automatic.md)
- Multiple components share same default object → See [provide-inject-default-value-factory](reference/provide-inject-default-value-factory.md)
### Attrs
- Both internal and fallthrough event handlers execute → See [attrs-event-listener-merging](reference/attrs-event-listener-merging.md)
- Explicit attributes overwritten by fallthrough values → See [fallthrough-attrs-overwrite-vue3](reference/fallthrough-attrs-overwrite-vue3.md)
- Attributes applying to wrong element in wrappers → See [inheritattrs-false-for-wrapper-components](reference/inheritattrs-false-for-wrapper-components.md)
### Composables
- Composable called outside setup context or asynchronously → See [composable-call-location-restrictions](reference/composable-call-location-restrictions.md)
- Composable reactive dependency not updating when input changes → See [composable-tovalue-inside-watcheffect](reference/composable-tovalue-inside-watcheffect.md)
- Composable mutates external state unexpectedly → See [composable-avoid-hidden-side-effects](reference/composable-avoid-hidden-side-effects.md)
- Destructuring composable returns breaks reactivity unexpectedly → See [composable-naming-return-pattern](reference/composable-naming-return-pattern.md)
### Composition API
- Lifecycle hooks failing silently after async operations → See [composition-api-script-setup-async-context](reference/composition-api-script-setup-async-context.md)
- Parent component refs unable to access exposed properties → See [define-expose-before-await](reference/define-expose-before-await.md)
- Functional-programming patterns break expected Vue reactivity behavior → See [composition-api-not-functional-programming](reference/composition-api-not-functional-programming.md)
- React Hook mental model causes incorrect Composition API usage → See [composition-api-vs-react-hooks-differences](reference/composition-api-vs-react-hooks-differences.md)
### Animation
- Animations fail to trigger when DOM nodes are reused → See [animation-key-for-rerender](reference/animation-key-for-rerender.md)
- TransitionGroup list updates feel laggy under load → See [animation-transitiongroup-performance](reference/animation-transitiongroup-performance.md)
### TypeScript
- Mutable prop defaults leak state between component instances → See [ts-withdefaults-mutable-factory-function](reference/ts-withdefaults-mutable-factory-function.md)
- reactive() generic typing causes ref unwrapping mismatches → See [ts-reactive-no-generic-argument](reference/ts-reactive-no-generic-argument.md)
- Template refs throw null access errors before mount or after v-if unmount → See [ts-template-ref-null-handling](reference/ts-template-ref-null-handling.md)
- Optional boolean props behave as false instead of undefined → See [ts-defineprops-boolean-default-false](reference/ts-defineprops-boolean-default-false.md)
- Imported defineProps types fail with unresolvable or complex type references → See [ts-defineprops-imported-types-limitations](reference/ts-defineprops-imported-types-limitations.md)
- Untyped DOM event handlers fail under strict TypeScript settings → See [ts-event-handler-explicit-typing](reference/ts-event-handler-explicit-typing.md)
- Dynamic component refs trigger reactive component warnings → See [ts-shallowref-for-dynamic-components](reference/ts-shallowref-for-dynamic-components.md)
- Union-typed template expressions fail type checks without narrowing → See [ts-template-type-casting](reference/ts-template-type-casting.md)
### Async Components
- Route components misconfigured with defineAsyncComponent lazy loading → See [async-component-vue-router](reference/async-component-vue-router.md)
- Network failures or timeouts loading components → See [async-component-error-handling](reference/async-component-error-handling.md)
- Template refs undefined after component reactivation → See [async-component-keepalive-ref-issue](reference/async-component-keepalive-ref-issue.md)
### Render Functions
- Render function output stays static after state changes → See [rendering-render-function-return-from-setup](reference/rendering-render-function-return-from-setup.md)
- Reused vnode instances render incorrectly → See [render-function-vnodes-must-be-unique](reference/render-function-vnodes-must-be-unique.md)
- String component names render as HTML elements → See [rendering-resolve-component-for-string-names](reference/rendering-resolve-component-for-string-names.md)
- Accessing vnode internals breaks on Vue updates → See [render-function-avoid-internal-vnode-properties](reference/render-function-avoid-internal-vnode-properties.md)
- Vue 2 render function patterns crash in Vue 3 → See [rendering-render-function-h-import-vue3](reference/rendering-render-function-h-import-vue3.md)
- Slot content not rendering from h() → See [rendering-render-function-slots-as-functions](reference/rendering-render-function-slots-as-functions.md)
### KeepAlive
- Child components mount twice with nested Vue Router routes → See [keepalive-router-nested-double-mount](reference/keepalive-router-nested-double-mount.md)
- Memory grows when combining KeepAlive with Transition animations → See [keepalive-transition-memory-leak](reference/keepalive-transition-memory-leak.md)
### Transitions
- JavaScript transition hooks hang without done callback → See [transition-js-hooks-done-callback](reference/transition-js-hooks-done-callback.md)
- Move animations fail on inline list elements → See [transition-group-flip-inline-elements](reference/transition-group-flip-inline-elements.md)
- List items jump instead of smoothly animating → See [transition-group-move-animation-position-absolute](reference/transition-group-move-animation-position-absolute.md)
- Vue 2 to Vue 3 TransitionGroup wrapper changes break layout → See [transition-group-no-default-wrapper-vue3](reference/transition-group-no-default-wrapper-vue3.md)
- Nested transitions cut off before finishing → See [transition-nested-duration](reference/transition-nested-duration.md)
- Scoped styles stop working in reusable transition wrappers → See [transition-reusable-scoped-style](reference/transition-reusable-scoped-style.md)
- RouterView transitions animate unexpectedly on first render → See [transition-router-view-appear](reference/transition-router-view-appear.md)
- Mixing CSS transitions and animations causes timing issues → See [transition-type-when-mixed](reference/transition-type-when-mixed.md)
- Cleanup hooks missed during rapid transition swaps → See [transition-unmount-hook-timing](reference/transition-unmount-hook-timing.md)
### Teleport
- Teleport target element not found in DOM → See [teleport-target-must-exist](reference/teleport-target-must-exist.md)
- Teleported content breaks SSR hydration → See [teleport-ssr-hydration](reference/teleport-ssr-hydration.md)
- Scoped styles not applying to teleported content → See [teleport-scoped-styles-limitation](reference/teleport-scoped-styles-limitation.md)
### Suspense
- Need to handle async errors from Suspense components → See [suspense-no-builtin-error-handling](reference/suspense-no-builtin-error-handling.md)
- Using Suspense with server-side rendering → See [suspense-ssr-hydration-issues](reference/suspense-ssr-hydration-issues.md)
- Async component loading/error UI ignored under Suspense → See [async-component-suspense-control](reference/async-component-suspense-control.md)
### SSR
- HTML differs between server and client renders → See [ssr-hydration-mismatch-causes](reference/ssr-hydration-mismatch-causes.md)
- User state leaks between requests from shared singleton stores → See [state-ssr-cross-request-pollution](reference/state-ssr-cross-request-pollution.md)
- Browser-only APIs crash server rendering in universal code paths → See [ssr-platform-specific-apis](reference/ssr-platform-specific-apis.md)
### Performance
- List children re-render unnecessarily because parent passes unstable props → See [perf-props-stability-update-optimization](reference/perf-props-stability-update-optimization.md)
- Computed objects retrigger effects despite equivalent values → See [perf-computed-object-stability](reference/perf-computed-object-stability.md)
### SFC (Single File Components)
- Trying to use named exports from component script blocks → See [sfc-named-exports-forbidden](reference/sfc-named-exports-forbidden.md)
- Variables not updating in template after changes → See [sfc-script-setup-reactivity](reference/sfc-script-setup-reactivity.md)
- Scoped styles not applying to child component elements → See [sfc-scoped-css-child-component-styling](reference/sfc-scoped-css-child-component-styling.md)
- Scoped styles not applying to dynamic v-html content → See [sfc-scoped-css-dynamic-content](reference/sfc-scoped-css-dynamic-content.md)
- Scoped styles not applying to slot content → See [sfc-scoped-css-slot-content](reference/sfc-scoped-css-slot-content.md)
- Tailwind classes missing when built dynamically → See [tailwind-dynamic-class-generation](reference/tailwind-dynamic-class-generation.md)
- Recursive components not rendering due to name conflicts → See [self-referencing-component-name](reference/self-referencing-component-name.md)
### Plugins
- Debugging why global properties cause naming conflicts → See [plugin-global-properties-sparingly](reference/plugin-global-properties-sparingly.md)
- Plugin not working or inject returns undefined → See [plugin-install-before-mount](reference/plugin-install-before-mount.md)
- Plugin global properties are unavailable in setup-based components → See [plugin-prefer-provide-inject-over-global-properties](reference/plugin-prefer-provide-inject-over-global-properties.md)
- Plugin type augmentation mistakes break ComponentCustomProperties typing → See [plugin-typescript-type-augmentation](reference/plugin-typescript-type-augmentation.md)
### App Configuration
- App configuration methods not working after mount call → See [configure-app-before-mount](reference/configure-app-before-mount.md)
- Chaining app config off mount() fails because mount returns component instance → See [mount-return-value](reference/mount-return-value.md)
- require.context-based component auto-registration fails in Vite → See [dynamic-component-registration-vite](reference/dynamic-component-registration-vite.md)
@@ -0,0 +1,160 @@
---
title: Use Key Attribute to Force Re-render Animations
impact: MEDIUM
impactDescription: Without key attributes, Vue reuses DOM elements and animation libraries like AutoAnimate cannot detect changes to animate
type: gotcha
tags: [vue3, animation, key, autoanimate, rerender, dom]
---
# Use Key Attribute to Force Re-render Animations
**Impact: MEDIUM** - Vue optimizes performance by reusing DOM elements when possible. However, this optimization can prevent animation libraries (like AutoAnimate) from detecting changes, because the element is updated in place rather than re-created. Adding a `:key` attribute forces Vue to treat changed elements as new, triggering proper animations.
## Task Checklist
- [ ] Add `:key` to elements that should animate when their content changes
- [ ] Use unique, changing values for keys (not indices)
- [ ] For route transitions, add `:key="$route.fullPath"` to `<router-view>`
- [ ] Apply `v-auto-animate` to the parent element of keyed children
**Problematic Code:**
```vue
<template>
<!-- BAD: Text changes but no animation occurs -->
<div v-auto-animate>
<p>{{ message }}</p> <!-- No key - element is reused -->
</div>
<!-- BAD: Image source changes but no animation -->
<div v-auto-animate>
<img :src="imageUrl" /> <!-- No key - element is reused -->
</div>
<!-- BAD: Route changes don't animate -->
<router-view v-auto-animate /> <!-- No key -->
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello')
const imageUrl = ref('/images/photo1.jpg')
// Changing these won't trigger animations because
// Vue updates the existing elements rather than replacing them
</script>
```
**Correct Code:**
```vue
<template>
<!-- GOOD: Key forces re-render, triggering animation -->
<div v-auto-animate>
<p :key="message">{{ message }}</p>
</div>
<!-- GOOD: Image animates when source changes -->
<div v-auto-animate>
<img :key="imageUrl" :src="imageUrl" />
</div>
<!-- GOOD: Route changes animate properly -->
<router-view :key="$route.fullPath" v-auto-animate />
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello')
const imageUrl = ref('/images/photo1.jpg')
// Now changing these will trigger animations
function updateMessage() {
message.value = 'World' // Triggers enter animation for new <p>
}
</script>
```
## Why This Works
When Vue sees a `:key` change:
1. It considers the old element and new element as different
2. The old element is removed (triggering leave animation)
3. A new element is created (triggering enter animation)
Without `:key`:
1. Vue sees the same element type in the same position
2. It updates the element's properties in place
3. No DOM addition/removal occurs, so no animation triggers
## Common Use Cases
### Animating Text Content Changes
```vue
<template>
<div v-auto-animate>
<h1 :key="title">{{ title }}</h1>
<p :key="description">{{ description }}</p>
</div>
</template>
```
### Animating Dynamic Components
```vue
<template>
<div v-auto-animate>
<component :is="currentComponent" :key="currentComponent" />
</div>
</template>
```
### Animating Route Transitions
```vue
<template>
<router-view v-slot="{ Component, route }">
<div v-auto-animate>
<component :is="Component" :key="route.fullPath" />
</div>
</router-view>
</template>
```
## With Vue's Built-in Transition
The same principle applies to Vue's `<Transition>` component:
```vue
<template>
<!-- GOOD: Key triggers transition on content change -->
<Transition name="fade" mode="out-in">
<p :key="message">{{ message }}</p>
</Transition>
<!-- GOOD: Different keys for conditional content -->
<Transition name="fade" mode="out-in">
<div v-if="isLoading" key="loading">Loading...</div>
<div v-else key="content">{{ content }}</div>
</Transition>
</template>
```
## Caution: Performance Implications
Using `:key` forces full component re-creation. For frequently changing data:
- The entire component tree under the keyed element is destroyed and recreated
- Any component state is lost
- Consider whether the animation is worth the performance cost
```vue
<!-- Be cautious with complex components -->
<ComplexDashboard :key="refreshTrigger" />
<!-- This destroys and recreates the entire dashboard! -->
```
## Reference
- [Vue.js Animation Techniques](https://vuejs.org/guide/extras/animation.html)
- [AutoAnimate with Vue](https://auto-animate.formkit.com/#usage-vue)
- [Vue.js v-for with key](https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key)
@@ -0,0 +1,241 @@
---
title: TransitionGroup Performance with Large Lists and CSS Frameworks
impact: MEDIUM
impactDescription: TransitionGroup can cause noticeable DOM update lag when animating list changes, especially with CSS frameworks
type: gotcha
tags: [vue3, transition-group, animation, performance, list, css-framework]
---
# TransitionGroup Performance with Large Lists and CSS Frameworks
**Impact: MEDIUM** - Vue's `<TransitionGroup>` can experience significant DOM update lag when animating list changes, particularly when:
- Using CSS frameworks (Tailwind, Bootstrap, etc.)
- Performing array operations like `slice()` that change multiple items
- Working with larger lists
Without TransitionGroup, DOM updates occur instantly. With it, there can be noticeable delay before the UI reflects changes.
## Task Checklist
- [ ] For frequently updated lists, consider if transition animations are necessary
- [ ] Use CSS `content-visibility: auto` for long lists to reduce render cost
- [ ] Minimize CSS framework classes on list items during transitions
- [ ] Consider virtual scrolling for very large animated lists
- [ ] Profile with Vue DevTools to identify transition bottlenecks
**Problematic Pattern:**
```vue
<template>
<!-- Potentially slow with large lists or complex CSS -->
<TransitionGroup name="list" tag="ul">
<li
v-for="item in items"
:key="item.id"
class="p-4 m-2 rounded-lg shadow-md bg-gradient-to-r from-blue-500 to-purple-600
hover:shadow-lg transition-all duration-300 ease-in-out transform hover:scale-105
border border-gray-200 flex items-center justify-between"
>
{{ item.name }}
</li>
</TransitionGroup>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([/* many items */])
// Operations like slice can cause visible lag
function removeItems() {
items.value = items.value.slice(5) // May lag with TransitionGroup
}
</script>
<style>
.list-move,
.list-enter-active,
.list-leave-active {
transition: all 0.5s ease;
}
</style>
```
**Optimized Approach:**
```vue
<template>
<!-- Simpler classes, shorter transitions -->
<TransitionGroup name="list" tag="ul" class="relative">
<li
v-for="item in items"
:key="item.id"
class="list-item"
>
{{ item.name }}
</li>
</TransitionGroup>
</template>
<script setup>
import { ref, computed } from 'vue'
const items = ref([/* items */])
// For large batch operations, consider disabling animations temporarily
const isAnimating = ref(true)
</script>
<style>
/* Keep transition CSS simple and specific */
.list-item {
/* Minimal styles during animation */
padding: 1rem;
}
.list-move {
transition: transform 0.3s ease; /* Shorter duration */
}
.list-enter-active,
.list-leave-active {
transition: opacity 0.2s ease, transform 0.2s ease;
}
.list-enter-from,
.list-leave-to {
opacity: 0;
transform: translateX(-20px);
}
/* Use will-change sparingly */
.list-enter-active {
will-change: opacity, transform;
}
/* Absolute positioning for leaving elements prevents layout thrashing */
.list-leave-active {
position: absolute;
width: 100%;
}
</style>
```
## Performance Optimization Strategies
### 1. Skip Animations for Bulk Operations
```vue
<template>
<TransitionGroup v-if="animationsEnabled" name="list" tag="ul">
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</TransitionGroup>
<!-- Instant update without animations -->
<ul v-else>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
<script setup>
import { ref, nextTick } from 'vue'
const animationsEnabled = ref(true)
async function bulkUpdate(newItems) {
// Disable animations for bulk operations
animationsEnabled.value = false
items.value = newItems
await nextTick()
animationsEnabled.value = true
}
</script>
```
### 2. Virtual Scrolling for Large Lists
```vue
<template>
<!-- Use a virtual list library for large datasets -->
<RecycleScroller
:items="items"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div class="list-item">{{ item.name }}</div>
</RecycleScroller>
</template>
<script setup>
import { RecycleScroller } from 'vue-virtual-scroller'
</script>
```
### 3. Reduce CSS Complexity During Transitions
```vue
<style>
/* Move complex styles to a stable wrapper */
.list-item-wrapper {
@apply p-4 m-2 rounded-lg shadow-md bg-gradient-to-r from-blue-500 to-purple-600;
}
/* Keep animated element styles minimal */
.list-item {
/* Only essential layout styles */
}
.list-move,
.list-enter-active,
.list-leave-active {
/* Only animate transform/opacity - GPU accelerated */
transition: transform 0.3s ease, opacity 0.3s ease;
}
</style>
```
### 4. Use CSS content-visibility
```css
/* For very long lists, defer rendering of off-screen items */
.list-item {
content-visibility: auto;
contain-intrinsic-size: 0 50px; /* Estimated height */
}
```
## When to Avoid TransitionGroup
Consider alternatives when:
- List updates are frequent (real-time data)
- List contains 100+ items
- Items have complex CSS or nested components
- Performance is critical (mobile, low-end devices)
```vue
<!-- Simple alternative: CSS-only animations on individual items -->
<ul>
<li
v-for="item in items"
:key="item.id"
class="animate-in"
>
{{ item.name }}
</li>
</ul>
<style>
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-in {
animation: fadeIn 0.3s ease forwards;
}
</style>
```
## Reference
- [Vue.js TransitionGroup](https://vuejs.org/guide/built-ins/transition-group.html)
- [GitHub Issue: transition-group DOM update lag](https://github.com/vuejs/vue/issues/5845)
- [Vue Virtual Scroller](https://github.com/Akryum/vue-virtual-scroller)
@@ -0,0 +1,115 @@
# Async Component Error Handling
## Rule
Always configure error handling for async components using `errorComponent` and/or `onError` callback. Without proper error handling, failed component loads can leave the UI in an undefined state with no user feedback.
## Why This Matters
Network failures, timeouts, and server errors are common in production. Without error handling, users see blank spaces or broken UIs with no indication of what went wrong or how to recover.
## Bad Code
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
// No error handling - fails silently
const AsyncWidget = defineAsyncComponent(() =>
import('./Widget.vue')
)
</script>
```
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
// isLoading never becomes false on error - infinite spinner
const isLoading = ref(true)
const Widget = defineAsyncComponent({
loader: () => import('./Widget.vue').finally(() => {
isLoading.value = false // Only runs on success
})
})
</script>
```
## Good Code
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
import LoadingSpinner from './LoadingSpinner.vue'
import ErrorDisplay from './ErrorDisplay.vue'
const AsyncWidget = defineAsyncComponent({
loader: () => import('./Widget.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorDisplay,
delay: 200, // Prevent loading flicker
timeout: 10000 // Show error after 10 seconds
})
</script>
```
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
// With retry logic using onError
const AsyncWidget = defineAsyncComponent({
loader: () => import('./Widget.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorDisplay,
onError(error, retry, fail, attempts) {
if (attempts <= 3) {
// Retry up to 3 times
retry()
} else {
// Give up and show error component
fail()
}
}
})
</script>
```
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
// Fallback component pattern - catch in loader
const AsyncWidget = defineAsyncComponent(() =>
import('./Widget.vue').catch(() => import('./WidgetFallback.vue'))
)
</script>
```
## onError Callback Parameters
The `onError` callback receives four arguments:
| Parameter | Type | Description |
|-----------|------|-------------|
| `error` | `Error` | The error that caused the load to fail |
| `retry` | `Function` | Call to retry loading the component |
| `fail` | `Function` | Call to give up and show errorComponent |
| `attempts` | `number` | Number of load attempts so far |
## Key Points
1. Always provide an `errorComponent` for production applications
2. Use `timeout` to prevent indefinite loading states
3. Consider retry logic with `onError` for transient network issues
4. The `delay` option (default 200ms) prevents loading flicker on fast networks
5. Use the fallback pattern (`.catch()` in loader) when you want a seamless degradation
## SSR Warning
Using `onError` with SSR can cause issues in some configurations, potentially leading to infinite loading. Test thoroughly in SSR environments.
## References
- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async)
- [Handling Async Components' loading errors](https://awad.dev/blog/handling-async-component-loading-errors/)
@@ -0,0 +1,112 @@
# Async Components with keep-alive Ref Issues
## Rule
When using `<keep-alive>`, `<component>`, and `defineAsyncComponent` together, be aware that template refs can become undefined when the component is re-activated after being deactivated.
## Why This Matters
This is a known Vue issue where the ref binding works correctly on first activation but becomes undefined on subsequent activations. This can cause runtime errors when trying to access component methods or properties through refs.
## Problem Scenario
```vue
<script setup>
import { ref, defineAsyncComponent } from 'vue'
const AsyncWidget = defineAsyncComponent(() =>
import('./Widget.vue')
)
const currentComponent = ref(AsyncWidget)
const widgetRef = ref(null)
function callWidgetMethod() {
// May be undefined after component reactivation!
widgetRef.value?.doSomething()
}
</script>
<template>
<keep-alive>
<component :is="currentComponent" ref="widgetRef" />
</keep-alive>
</template>
```
## Workarounds
### Option 1: Use onActivated to re-establish ref access
```vue
<script setup>
import { ref, defineAsyncComponent, onActivated, nextTick } from 'vue'
const AsyncWidget = defineAsyncComponent(() =>
import('./Widget.vue')
)
const currentComponent = ref(AsyncWidget)
const widgetRef = ref(null)
// Use a computed or method that waits for ref to be available
async function callWidgetMethod() {
await nextTick()
if (widgetRef.value) {
widgetRef.value.doSomething()
}
}
</script>
```
### Option 2: Avoid mixing all three patterns
If possible, use one of these alternatives:
```vue
<!-- Option A: Don't use keep-alive with async components -->
<template>
<component :is="currentComponent" ref="widgetRef" />
</template>
<!-- Option B: Use static component with keep-alive -->
<script setup>
import Widget from './Widget.vue' // Regular import
</script>
<template>
<keep-alive>
<component :is="Widget" ref="widgetRef" />
</keep-alive>
</template>
```
### Option 3: Use provide/inject instead of refs
```vue
<!-- Parent.vue -->
<script setup>
import { provide, ref } from 'vue'
const sharedState = ref({ /* shared data */ })
provide('widgetState', sharedState)
</script>
<!-- Widget.vue (async component) -->
<script setup>
import { inject } from 'vue'
const widgetState = inject('widgetState')
</script>
```
## Key Points
1. This is a known issue when combining `<keep-alive>`, `<component :is>`, and `defineAsyncComponent`
2. Refs may become undefined after component deactivation/reactivation
3. Use `nextTick` and null checks when accessing refs
4. Consider alternative patterns like provide/inject for cross-component communication
5. Test thoroughly when using this combination
## References
- [Vue.js GitHub Discussion #11334](https://github.com/orgs/vuejs/discussions/11334)
- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async)
@@ -0,0 +1,84 @@
---
title: Suspense Overrides Async Component Loading and Error Options
impact: MEDIUM
impactDescription: Async component loading/error options are ignored under a parent Suspense, leading to missing spinners and error UIs
type: gotcha
tags: [vue3, suspense, async-components, loading, error-handling]
---
# Suspense Overrides Async Component Loading and Error Options
**Impact: MEDIUM** - When an async component renders inside a parent `<Suspense>`, its `loadingComponent`, `errorComponent`, `delay`, and `timeout` options do not run. The parent Suspense controls loading and error UX instead.
## Task Checklist
- [ ] Confirm whether the async component is inside a `<Suspense>` boundary
- [ ] Use `suspensible: false` when the component must manage its own loading/error UI
- [ ] Or move loading/error UI to the parent `<Suspense>` fallback and an error boundary (`onErrorCaptured`)
- [ ] Provide a retry path for failed loads
**Incorrect:**
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
const AsyncDashboard = defineAsyncComponent({
loader: () => import('./Dashboard.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorDisplay,
timeout: 3000
})
</script>
<template>
<Suspense>
<AsyncDashboard />
<template #fallback>Loading...</template>
</Suspense>
</template>
```
**Correct (component handles its own states):**
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
const AsyncDashboard = defineAsyncComponent({
loader: () => import('./Dashboard.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorDisplay,
timeout: 3000,
suspensible: false
})
</script>
<template>
<AsyncDashboard />
</template>
```
**Correct (parent Suspense owns loading/error UI):**
```vue
<script setup>
import { onErrorCaptured, ref } from 'vue'
import AsyncDashboard from './AsyncDashboard.vue'
const error = ref(null)
onErrorCaptured((err) => {
error.value = err
return false
})
</script>
<template>
<ErrorDisplay v-if="error" :error="error" />
<Suspense v-else>
<AsyncDashboard />
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
</template>
```
@@ -0,0 +1,109 @@
# Do Not Use defineAsyncComponent with Vue Router
## Rule
Never use `defineAsyncComponent` when configuring Vue Router route components. Vue Router has its own lazy loading mechanism using dynamic imports directly.
## Why This Matters
Vue Router's lazy loading is specifically designed for route-level code splitting. Using `defineAsyncComponent` for routes adds unnecessary overhead and can cause unexpected behavior with navigation guards, loading states, and route transitions.
## Bad Code
```javascript
import { defineAsyncComponent } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/dashboard',
// WRONG: Don't use defineAsyncComponent here
component: defineAsyncComponent(() =>
import('./views/Dashboard.vue')
)
},
{
path: '/profile',
// WRONG: This also won't work as expected
component: defineAsyncComponent({
loader: () => import('./views/Profile.vue'),
loadingComponent: LoadingSpinner
})
}
]
})
```
## Good Code
```javascript
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/dashboard',
// CORRECT: Use dynamic import directly
component: () => import('./views/Dashboard.vue')
},
{
path: '/profile',
// CORRECT: Simple arrow function with import
component: () => import('./views/Profile.vue')
}
]
})
```
## Handling Loading States with Vue Router
For route-level loading states, use Vue Router's navigation guards or a global loading indicator:
```vue
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const isLoading = ref(false)
router.beforeEach(() => {
isLoading.value = true
})
router.afterEach(() => {
isLoading.value = false
})
</script>
<template>
<LoadingBar v-if="isLoading" />
<RouterView />
</template>
```
## When to Use defineAsyncComponent
Use `defineAsyncComponent` for:
- Components loaded conditionally within a page
- Heavy components that aren't always needed
- Modal dialogs or panels that load on demand
Use Vue Router's lazy loading for:
- Route-level components (views/pages)
- Any component configured in route definitions
## Key Points
1. Vue Router and `defineAsyncComponent` are separate lazy loading mechanisms
2. Route components should use direct dynamic imports: `() => import('./View.vue')`
3. Use navigation guards for route-level loading indicators
4. `defineAsyncComponent` is for component-level lazy loading within pages
## References
- [Vue Router Lazy Loading Routes](https://router.vuejs.org/guide/advanced/lazy-loading.html)
- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async)
@@ -0,0 +1,205 @@
# Fallthrough Event Listeners Are Additive
## Rule
When an event listener is passed to a component as a fallthrough attribute, it is added to the root element's existing listeners of the same type - both will trigger. This is different from props where values are replaced. Be aware that both the component's internal handler and the parent's handler will execute.
## Why This Matters
- Developers may expect event listeners to override like props
- Both handlers execute, which can cause double submissions, duplicate API calls
- Order of execution: internal handler first, then fallthrough handler
- This is actually useful for composition but can cause bugs if unexpected
## Bad Code
```vue
<!-- BaseButton.vue - Potential double-action bug -->
<template>
<button @click="internalClick">
<slot />
</button>
</template>
<script setup>
const emit = defineEmits(['action'])
function internalClick() {
// This runs first
emit('action')
console.log('Internal click handler')
}
</script>
<!-- Parent.vue -->
<template>
<BaseButton @click="parentClick">Submit</BaseButton>
</template>
<script setup>
function parentClick() {
// This ALSO runs (after internal)
submitForm() // Might cause double submission!
console.log('Parent click handler')
}
</script>
<!--
RESULT: Both handlers fire!
Console output:
1. "Internal click handler"
2. "Parent click handler"
If both trigger API calls, you get duplicate requests
-->
```
## Good Code
### Option 1: Prevent fallthrough with inheritAttrs: false
```vue
<!-- BaseButton.vue - Control event handling explicitly -->
<script setup>
defineOptions({
inheritAttrs: false
})
const emit = defineEmits(['click'])
function handleClick(event) {
// Component controls all click behavior
console.log('Handled internally')
emit('click', event) // Explicitly forward if needed
}
</script>
<template>
<button @click="handleClick">
<slot />
</button>
</template>
```
### Option 2: Document the additive behavior
```vue
<!-- BaseButton.vue - Design for composition -->
<script setup>
/**
* BaseButton - A composable button component
*
* Note: Click handlers passed to this component are ADDITIVE.
* The internal handler runs first, then any parent @click handler.
* Use @action event if you only want to respond to the action.
*/
const emit = defineEmits(['action'])
function internalClick() {
// Internal logic (e.g., ripple effect, analytics)
emit('action')
}
</script>
<template>
<button @click="internalClick">
<slot />
</button>
</template>
<!-- Parent.vue - Use the custom event instead -->
<template>
<!-- Use @action, not @click, to avoid double handling -->
<BaseButton @action="handleAction">Submit</BaseButton>
</template>
```
### Option 3: Use stopPropagation if needed
```vue
<!-- BaseButton.vue - Stop event propagation when needed -->
<script setup>
const props = defineProps({
stopPropagation: Boolean
})
function handleClick(event) {
if (props.stopPropagation) {
event.stopPropagation()
}
// Internal handling...
}
</script>
<template>
<button @click="handleClick">
<slot />
</button>
</template>
```
## Using Additive Behavior Intentionally
The additive behavior can be useful for extending functionality:
```vue
<!-- EnhancedButton.vue - Leveraging additive listeners -->
<template>
<button
@click="trackClick"
@focus="trackFocus"
>
<slot />
</button>
</template>
<script setup>
function trackClick() {
analytics.track('button_click')
// Parent's @click will also run - that's intentional!
}
function trackFocus() {
analytics.track('button_focus')
}
</script>
<!-- Parent.vue -->
<template>
<!-- Both analytics AND form submission happen -->
<EnhancedButton @click="submitForm">Submit</EnhancedButton>
</template>
```
## Execution Order
```vue
<script setup>
// Component
function componentHandler() {
console.log('1. Component handler (first)')
}
</script>
<template>
<button @click="componentHandler">Click</button>
</template>
<!-- Parent passes @click -->
<!-- Execution order:
1. componentHandler (defined in component)
2. parentHandler (passed as fallthrough)
-->
```
## Best Practices
1. **For UI components**: Use `inheritAttrs: false` and emit custom events
2. **For HOCs/wrappers**: Document that listeners are additive
3. **For analytics/tracking**: Leverage additive behavior intentionally
4. **Avoid side effects**: Don't assume your handler is the only one running
## References
- [Fallthrough Attributes - v-on Listener Inheritance](https://vuejs.org/guide/components/attrs.html#v-on-listener-inheritance)
- [Component Events](https://vuejs.org/guide/components/events.html)
@@ -0,0 +1,118 @@
---
title: Checkbox true-value/false-value Not Submitted in Forms
impact: MEDIUM
impactDescription: true-value and false-value attributes don't affect form submission - unchecked boxes send nothing
type: capability
tags: [vue3, v-model, forms, checkbox, form-submission]
---
# Checkbox true-value/false-value Not Submitted in Forms
**Impact: MEDIUM** - Vue's `true-value` and `false-value` attributes only affect the JavaScript binding, NOT the actual form submission. Unchecked checkboxes are never included in form submissions by browsers, regardless of `false-value`.
This is a browser limitation, not a Vue issue. If you need to submit one of two values (like "yes"/"no" or "active"/"inactive"), use radio buttons instead of a checkbox.
## Task Checklist
- [ ] Don't rely on `false-value` for form submissions - it won't be sent
- [ ] Use radio buttons when you need to submit one of exactly two values
- [ ] Remember `true-value`/`false-value` are for JavaScript state only
- [ ] For form submissions with custom values, handle the transformation server-side or in submit handler
**Problem - false-value not submitted:**
```html
<script setup>
import { ref } from 'vue'
const status = ref('no') // JavaScript value works correctly
</script>
<template>
<form action="/api/update" method="POST">
<!-- PROBLEM: When unchecked, nothing is submitted for this field -->
<!-- Server receives no "status" field at all, not "no" -->
<input
type="checkbox"
v-model="status"
true-value="yes"
false-value="no"
name="status"
>
<label>Active</label>
<!-- status.value correctly shows "yes" or "no" in Vue -->
<!-- But form submission only sends "status=yes" when checked -->
<!-- When unchecked, "status" field is completely missing -->
</form>
</template>
```
**Solution 1 - Use radio buttons for two-value submission:**
```html
<script setup>
import { ref } from 'vue'
const status = ref('no')
</script>
<template>
<form action="/api/update" method="POST">
<!-- CORRECT: Radio buttons always submit a value -->
<label>
<input type="radio" v-model="status" value="yes" name="status">
Active
</label>
<label>
<input type="radio" v-model="status" value="no" name="status">
Inactive
</label>
<!-- Form always submits "status=yes" or "status=no" -->
</form>
</template>
```
**Solution 2 - Handle in submit handler (for SPA/AJAX):**
```html
<script setup>
import { ref } from 'vue'
const isActive = ref(false)
async function submitForm() {
// Transform checkbox state to desired value before sending
const payload = {
status: isActive.value ? 'yes' : 'no'
}
await fetch('/api/update', {
method: 'POST',
body: JSON.stringify(payload)
})
}
</script>
<template>
<!-- For AJAX submission, checkbox is fine - transform in handler -->
<input type="checkbox" v-model="isActive">
<label>Active</label>
<button @click="submitForm">Save</button>
</template>
```
**Solution 3 - Hidden input fallback:**
```html
<template>
<form action="/api/update" method="POST">
<!-- Hidden input provides fallback value -->
<input type="hidden" name="status" value="no">
<!-- Checkbox overrides with "yes" when checked -->
<input type="checkbox" name="status" value="yes" v-model="isActive">
<label>Active</label>
</form>
</template>
```
## Reference
- [Vue.js Form Input Bindings - Checkbox](https://vuejs.org/guide/essentials/forms.html#checkbox)
@@ -0,0 +1,172 @@
---
title: Clean Up Event Listeners and Intervals in onUnmounted
impact: HIGH
impactDescription: Failing to clean up side effects causes memory leaks and ghost event handlers
type: capability
tags: [vue3, lifecycle, memory-leak, event-listeners, intervals, cleanup]
---
# Clean Up Event Listeners and Intervals in onUnmounted
**Impact: HIGH** - Failing to clean up event listeners, intervals, timeouts, and subscriptions when a component unmounts causes memory leaks and ghost handlers that continue running, leading to performance degradation and subtle bugs in Single Page Applications.
When using custom events, timers, WebSocket connections, or third-party libraries, always clean up in `onUnmounted` (Composition API) or `unmounted` (Options API).
## Task Checklist
- [ ] Track all addEventListener calls and remove them in onUnmounted
- [ ] Clear all setInterval and setTimeout calls in onUnmounted
- [ ] Unsubscribe from external event emitters and observables
- [ ] Disconnect WebSocket connections and third-party library instances
- [ ] Use `onBeforeUnmount` if cleanup must happen before DOM removal
**Incorrect:**
```javascript
// Composition API - WRONG: No cleanup
import { onMounted } from 'vue'
export default {
setup() {
onMounted(() => {
// These keep running after component unmounts!
window.addEventListener('resize', handleResize)
setInterval(pollServer, 5000)
socket.on('message', handleMessage)
})
}
}
```
```javascript
// Options API - WRONG: No cleanup
export default {
mounted() {
window.addEventListener('scroll', this.handleScroll)
this.timer = setInterval(this.refresh, 10000)
}
// Component unmounts, but listeners and timers persist!
}
```
**Correct:**
```javascript
// Composition API - CORRECT: Proper cleanup
import { onMounted, onUnmounted, ref } from 'vue'
export default {
setup() {
const intervalId = ref(null)
const handleResize = () => {
// handle resize
}
const handleMessage = (msg) => {
// handle message
}
onMounted(() => {
window.addEventListener('resize', handleResize)
intervalId.value = setInterval(pollServer, 5000)
socket.on('message', handleMessage)
})
onUnmounted(() => {
// Clean up everything!
window.removeEventListener('resize', handleResize)
if (intervalId.value) {
clearInterval(intervalId.value)
}
socket.off('message', handleMessage)
})
}
}
```
```javascript
// Options API - CORRECT: Proper cleanup
export default {
data() {
return {
timer: null
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
this.timer = setInterval(this.refresh, 10000)
},
unmounted() {
window.removeEventListener('scroll', this.handleScroll)
if (this.timer) {
clearInterval(this.timer)
}
},
methods: {
handleScroll() { /* ... */ },
refresh() { /* ... */ }
}
}
```
## Using Composable Pattern for Auto-Cleanup
```javascript
// Reusable composable with automatic cleanup
import { onMounted, onUnmounted } from 'vue'
export function useEventListener(target, event, handler) {
onMounted(() => {
target.addEventListener(event, handler)
})
onUnmounted(() => {
target.removeEventListener(event, handler)
})
}
export function useInterval(callback, delay) {
let intervalId = null
onMounted(() => {
intervalId = setInterval(callback, delay)
})
onUnmounted(() => {
if (intervalId) clearInterval(intervalId)
})
}
// Usage - cleanup is automatic
import { useEventListener, useInterval } from './composables'
export default {
setup() {
useEventListener(window, 'resize', handleResize)
useInterval(pollServer, 5000)
// No manual cleanup needed!
}
}
```
## VueUse Alternative
```javascript
// VueUse provides cleanup-aware composables
import { useEventListener, useIntervalFn } from '@vueuse/core'
export default {
setup() {
// Automatically cleaned up on unmount
useEventListener(window, 'resize', handleResize)
const { pause, resume } = useIntervalFn(pollServer, 5000)
// Also provides pause/resume controls
}
}
```
## Reference
- [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html)
- [VueUse - useEventListener](https://vueuse.org/core/useEventListener/)
@@ -0,0 +1,180 @@
---
title: Click Events on Custom Components Require Emit or Fallthrough
impact: HIGH
impactDescription: Native click events on custom components won't work without proper emit declaration or attribute fallthrough
type: gotcha
tags: [vue3, events, components, emit, click, migration]
---
# Click Events on Custom Components Require Emit or Fallthrough
**Impact: HIGH** - Unlike native HTML elements, custom Vue components don't automatically forward native DOM events like `click`. You must either emit the event explicitly, rely on attribute fallthrough to a single root element, or use the `.native` modifier (Vue 2 only, removed in Vue 3). This is a common source of confusion and migration issues.
## Task Checklist
- [ ] Declare emitted events using `defineEmits` in child components
- [ ] Emit click events from child component when needed
- [ ] Understand that single-root components automatically forward attrs to root
- [ ] Remove `.native` modifier when migrating from Vue 2 to Vue 3
- [ ] For multi-root components, explicitly bind `$attrs` or emit events
**Incorrect:**
```html
<!-- WRONG: Expecting native click to work on custom component -->
<template>
<MyButton @click="handleClick">Click me</MyButton>
<!-- This may not work as expected! -->
</template>
```
```html
<!-- WRONG: Vue 2 .native modifier doesn't exist in Vue 3 -->
<template>
<MyButton @click.native="handleClick">Click me</MyButton>
<!-- Error in Vue 3: .native modifier removed -->
</template>
```
```html
<!-- WRONG: Multi-root component with no attr binding -->
<!-- MyButton.vue -->
<template>
<span>Icon</span>
<button>{{ label }}</button>
<!-- No root element to receive click! -->
</template>
```
**Correct:**
```html
<!-- CORRECT: Child component emits the click event -->
<!-- MyButton.vue -->
<template>
<button @click="$emit('click', $event)">
<slot></slot>
</button>
</template>
<script setup>
defineEmits(['click'])
</script>
<!-- Parent.vue -->
<template>
<MyButton @click="handleClick">Click me</MyButton>
</template>
```
```html
<!-- CORRECT: Single root element with automatic fallthrough -->
<!-- MyButton.vue -->
<template>
<button>
<slot></slot>
</button>
<!-- @click from parent automatically falls through to button -->
</template>
<!-- Parent.vue -->
<template>
<MyButton @click="handleClick">Click me</MyButton>
</template>
```
```html
<!-- CORRECT: Multi-root component with explicit $attrs binding -->
<!-- MyButton.vue -->
<template>
<span>Icon</span>
<button v-bind="$attrs">
<slot></slot>
</button>
</template>
<script setup>
defineOptions({
inheritAttrs: false
})
</script>
```
## Component Events Don't Bubble
```javascript
// Important: Component-emitted events do NOT bubble
// You can only listen to events from direct children
// WRONG: Trying to catch grandchild events
<GrandParent @child-event="handle"> <!-- Won't receive! -->
<Parent>
<Child @click="$emit('child-event')" />
</Parent>
</GrandParent>
// CORRECT: Each level must relay the event
<GrandParent @child-event="handle">
<Parent @child-event="$emit('child-event', $event)">
<Child @click="$emit('child-event')" />
</Parent>
</GrandParent>
```
## Vue 3 Native Event Behavior
```javascript
// In Vue 3, if you declare an event in emits:
defineEmits(['click'])
// Then @click on the component ONLY listens to emitted events
// NOT native click events
// If you don't declare 'click' in emits:
defineEmits(['custom-event'])
// Then @click on single-root component will:
// 1. Fall through to root element as native listener
// 2. Fire on native click
```
## Composition API Emit Pattern
```vue
<script setup>
// Define what events this component emits
const emit = defineEmits(['click', 'update', 'delete'])
function handleClick(event) {
// Do component logic
processClick()
// Then emit to parent
emit('click', event)
}
</script>
<template>
<button @click="handleClick">
<slot></slot>
</button>
</template>
```
## Migration from Vue 2
```html
<!-- Vue 2: Used .native for native events on components -->
<MyComponent @click.native="handleClick" />
<!-- Vue 3: Remove .native, ensure component handles the event -->
<MyComponent @click="handleClick" />
<!-- Make sure MyComponent either:
1. Has single root that receives fallthrough attrs
2. Explicitly emits 'click' event
3. Uses v-bind="$attrs" on intended element -->
```
## Reference
- [Vue.js Component Events](https://vuejs.org/guide/components/events.html)
- [Vue.js Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
- [Vue 3 Migration - .native Modifier Removed](https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html)
@@ -0,0 +1,159 @@
---
title: Avoid Component Naming Conflicts Between Global and Local
impact: HIGH
impactDescription: Naming conflicts cause unexpected component rendering and hard-to-debug issues
type: gotcha
tags: [vue3, component-registration, naming-conflicts, global-local, debugging]
---
# Avoid Component Naming Conflicts Between Global and Local
**Impact: HIGH** - When a global component and a local component have the same name (or resolve to the same name due to casing differences), unexpected behavior occurs. The precedence rules can be confusing, and the wrong component may render silently without any error. This is particularly problematic when using third-party component libraries.
## Task Checklist
- [ ] Use unique, prefixed names for global components (e.g., `BaseButton`, `AppHeader`)
- [ ] Check for naming conflicts when adding global components
- [ ] Explicitly alias local components if there's potential conflict
- [ ] When overriding third-party components, document and test thoroughly
**Incorrect:**
```javascript
// main.js
import { createApp } from 'vue'
import Button from './components/Button.vue'
const app = createApp(App)
app.component('Button', Button) // Global Button
```
```vue
<!-- SomeComponent.vue -->
<script setup>
// This local Button might conflict with global Button
import Button from './local/Button.vue'
</script>
<template>
<!-- Which Button renders? Behavior may be unexpected -->
<Button>Click me</Button>
</template>
```
```vue
<!-- Another confusing scenario -->
<script setup>
// Registering with camelCase
import MyButton from './MyButton.vue'
</script>
<template>
<!-- Using kebab-case - might match a global 'my-button' instead -->
<my-button>Click</my-button>
</template>
```
**Correct:**
```javascript
// main.js - use prefixes for global components
import { createApp } from 'vue'
import BaseButton from './components/BaseButton.vue'
import BaseIcon from './components/BaseIcon.vue'
const app = createApp(App)
app.component('BaseButton', BaseButton)
app.component('BaseIcon', BaseIcon)
```
```vue
<!-- SomeComponent.vue -->
<script setup>
// Local components have distinct names
import SubmitButton from './local/SubmitButton.vue'
</script>
<template>
<!-- No ambiguity - each name is unique -->
<BaseButton>Generic button</BaseButton>
<SubmitButton>Submit form</SubmitButton>
</template>
```
## Explicit Aliasing for Clarity
When you intentionally want to override or have similar names, use explicit aliasing:
```vue
<script setup>
// Explicit alias to avoid confusion
import { default as LocalButton } from './Button.vue'
</script>
<template>
<LocalButton>Local version</LocalButton>
</template>
```
```vue
<!-- Options API with explicit component name -->
<script>
import ThirdPartyModal from 'some-library'
import CustomModal from './CustomModal.vue'
export default {
components: {
// Explicit names prevent ambiguity
LibraryModal: ThirdPartyModal,
CustomModal
}
}
</script>
```
## Resolution Order
Understanding Vue's component resolution order helps debug issues:
1. **Local registration** takes precedence over global
2. **Exact case match** takes precedence over case-insensitive match
3. Self-referencing component name (file name) has lowest priority
```vue
<!-- If all exist: GlobalButton, local Button, and file is Button.vue -->
<script setup>
import Button from './Button.vue' // Local registration
</script>
<template>
<!-- Resolves to locally imported Button, not global -->
<Button />
</template>
```
## Third-Party Library Conflicts
```vue
<script setup>
// Be explicit when using components from multiple libraries
import { Button as AntButton } from 'ant-design-vue'
import { Button as ElButton } from 'element-plus'
</script>
<template>
<AntButton>Ant Design</AntButton>
<ElButton>Element Plus</ElButton>
</template>
```
## Naming Convention Strategy
| Component Type | Naming Pattern | Example |
|----------------|---------------|---------|
| Base/Global | `Base*` or `App*` prefix | `BaseButton`, `AppHeader` |
| Domain-specific | Domain prefix | `UserCard`, `ProductList` |
| Page components | `*Page` or `*View` suffix | `HomePage`, `UserView` |
| Layout components | `*Layout` suffix | `DefaultLayout`, `AdminLayout` |
## Reference
- [Vue.js Component Registration](https://vuejs.org/guide/components/registration.html)
- [GitHub Issue: Global component naming conflicts](https://github.com/vuejs/vue/issues/4434)
@@ -0,0 +1,176 @@
---
title: Component Refs Require defineExpose with Script Setup
impact: HIGH
impactDescription: Parent components cannot access child ref properties unless explicitly exposed
type: gotcha
tags: [vue3, template-refs, script-setup, defineExpose, component-communication]
---
# Component Refs Require defineExpose with Script Setup
**Impact: HIGH** - Components using `<script setup>` are private by default. A parent component using a template ref to access a child will get an empty object unless the child explicitly exposes properties using `defineExpose()`. This is a fundamental change from Options API behavior.
This catches many developers off-guard when migrating from Options API, where `this.$refs.child` gave full access to the child instance.
## Task Checklist
- [ ] Use `defineExpose()` to explicitly expose properties/methods to parent refs
- [ ] Only expose what's necessary - keep component internals private
- [ ] Document exposed APIs as they form your component's public interface
- [ ] Prefer props/emit for parent-child communication; use refs sparingly
- [ ] Call defineExpose before any await operation (see async caveat)
**Incorrect:**
```vue
<!-- ChildComponent.vue -->
<script setup>
import { ref } from 'vue'
const count = ref(0)
const internalState = ref('private')
function increment() {
count.value++
}
function reset() {
count.value = 0
}
// WRONG: Nothing exposed - parent ref sees empty object
</script>
<template>
<div>{{ count }}</div>
</template>
```
```vue
<!-- ParentComponent.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)
onMounted(() => {
// WRONG: childRef.value is {} - empty object!
console.log(childRef.value.count) // undefined
childRef.value.increment() // TypeError: not a function
})
</script>
<template>
<ChildComponent ref="childRef" />
</template>
```
**Correct:**
```vue
<!-- ChildComponent.vue -->
<script setup>
import { ref } from 'vue'
const count = ref(0)
const internalState = ref('private') // Keep this private
function increment() {
count.value++
}
function reset() {
count.value = 0
}
// CORRECT: Explicitly expose public API
defineExpose({
count, // Expose the ref
increment, // Expose methods
reset
// internalState NOT exposed - stays private
})
</script>
<template>
<div>{{ count }}</div>
</template>
```
```vue
<!-- ParentComponent.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)
onMounted(() => {
// CORRECT: Can access exposed properties
console.log(childRef.value.count) // 0
childRef.value.increment() // Works!
// internalState is not accessible (private)
console.log(childRef.value.internalState) // undefined
})
</script>
<template>
<ChildComponent ref="childRef" />
</template>
```
```vue
<!-- Input wrapper example - exposing native element -->
<script setup>
import { ref } from 'vue'
const inputEl = ref(null)
// Expose the native input for parent to access (e.g., for focus)
defineExpose({
focus: () => inputEl.value?.focus(),
blur: () => inputEl.value?.blur(),
// Or expose the element directly
el: inputEl
})
</script>
<template>
<input ref="inputEl" v-bind="$attrs" />
</template>
```
```javascript
// Options API equivalent using expose option
export default {
expose: ['count', 'increment', 'reset'],
data() {
return {
count: 0,
internalState: 'private'
}
},
methods: {
increment() { this.count++ },
reset() { this.count = 0 }
}
}
```
## Best Practice Reminder
Component refs create tight coupling between parent and child. Prefer standard patterns:
```vue
<!-- PREFERRED: Use props and emit for communication -->
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>
<!-- Only use refs for imperative actions like focus(), scrollTo(), etc. -->
```
## Reference
- [Vue.js Component Refs](https://vuejs.org/guide/essentials/template-refs.html#ref-on-component)
- [Script Setup - defineExpose](https://vuejs.org/api/sfc-script-setup.html#defineexpose)
@@ -0,0 +1,208 @@
---
title: Avoid Hidden Side Effects in Composables
impact: HIGH
impactDescription: Side effects hidden in composables make debugging difficult and create implicit coupling between components
type: best-practice
tags: [vue3, composables, composition-api, side-effects, provide-inject, global-state]
---
# Avoid Hidden Side Effects in Composables
**Impact: HIGH** - Composables should encapsulate stateful logic, not hide side effects that affect things outside their scope. Hidden side effects like modifying global state, using provide/inject internally, or manipulating the DOM directly make composables unpredictable and hard to debug.
When a composable has unexpected side effects, consumers can't reason about what calling it will do. This leads to bugs that are difficult to trace and composables that can't be safely reused.
## Task Checklist
- [ ] Avoid using provide/inject inside composables (make dependencies explicit)
- [ ] Don't modify Pinia/Vuex store state internally (accept store as parameter instead)
- [ ] Don't manipulate DOM directly (use template refs passed as arguments)
- [ ] Document any unavoidable side effects clearly
- [ ] Keep composables focused on returning reactive state and methods
**Incorrect:**
```javascript
// WRONG: Hidden provide/inject dependency
export function useTheme() {
// Consumer has no idea this depends on a provided theme
const theme = inject('theme') // What if nothing provides this?
const isDark = computed(() => theme?.mode === 'dark')
return { isDark }
}
// WRONG: Modifying global store internally
import { useUserStore } from '@/stores/user'
export function useLogin() {
const userStore = useUserStore()
async function login(credentials) {
const user = await api.login(credentials)
// Hidden side effect: modifying global state
userStore.setUser(user)
userStore.setToken(user.token)
// Consumer doesn't know the store was modified!
}
return { login }
}
// WRONG: Hidden DOM manipulation
export function useFocusTrap() {
onMounted(() => {
// Which element? Consumer has no control
document.querySelector('.modal')?.focus()
})
}
// WRONG: Hidden provide that affects descendants
export function useFormContext() {
const form = reactive({ values: {}, errors: {} })
// Components calling this have no idea it provides something
provide('form-context', form)
return form
}
```
**Correct:**
```javascript
// CORRECT: Explicit dependency injection
export function useTheme(injectedTheme) {
// If no theme passed, consumer must handle it
const theme = injectedTheme ?? { mode: 'light' }
const isDark = computed(() => theme.mode === 'dark')
return { isDark }
}
// Usage - dependency is explicit
const theme = inject('theme', { mode: 'light' })
const { isDark } = useTheme(theme)
// CORRECT: Return actions, let consumer decide when to call them
export function useLogin() {
const user = ref(null)
const token = ref(null)
const isLoading = ref(false)
const error = ref(null)
async function login(credentials) {
isLoading.value = true
error.value = null
try {
const response = await api.login(credentials)
user.value = response.user
token.value = response.token
return response
} catch (e) {
error.value = e
throw e
} finally {
isLoading.value = false
}
}
return { user, token, isLoading, error, login }
}
// Consumer decides what to do with the result
const { user, token, login } = useLogin()
const userStore = useUserStore()
async function handleLogin(credentials) {
await login(credentials)
// Consumer explicitly updates the store
userStore.setUser(user.value)
userStore.setToken(token.value)
}
// CORRECT: Accept element as parameter
export function useFocusTrap(targetRef) {
onMounted(() => {
targetRef.value?.focus()
})
onUnmounted(() => {
// Cleanup focus trap
})
}
// Usage - consumer controls which element
const modalRef = ref(null)
useFocusTrap(modalRef)
// CORRECT: Separate composable from provider
export function useFormContext() {
const form = reactive({ values: {}, errors: {} })
return form
}
// In parent component - explicit provide
const form = useFormContext()
provide('form-context', form)
```
## Acceptable Side Effects (With Documentation)
Some side effects are acceptable when they're the core purpose of the composable:
```javascript
/**
* Tracks mouse position globally.
*
* SIDE EFFECTS:
* - Adds 'mousemove' event listener to window (cleaned up on unmount)
*
* @returns {Object} Mouse coordinates { x, y }
*/
export function useMouse() {
const x = ref(0)
const y = ref(0)
// This side effect is the whole point of the composable
// and is properly cleaned up
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
function update(event) {
x.value = event.pageX
y.value = event.pageY
}
return { x, y }
}
```
## Pattern: Dependency Injection for Flexibility
```javascript
// Composable accepts its dependencies
export function useDataFetcher(apiClient, cache = null) {
const data = ref(null)
async function fetch(url) {
if (cache) {
const cached = cache.get(url)
if (cached) {
data.value = cached
return
}
}
data.value = await apiClient.get(url)
cache?.set(url, data.value)
}
return { data, fetch }
}
// Usage - dependencies are explicit and testable
const apiClient = inject('apiClient')
const cache = inject('cache', null)
const { data, fetch } = useDataFetcher(apiClient, cache)
```
## Reference
- [Vue.js Composables](https://vuejs.org/guide/reusability/composables.html)
- [Common Mistakes Creating Composition Functions](https://www.telerik.com/blogs/common-mistakes-creating-composition-functions-vue)
@@ -0,0 +1,141 @@
---
title: Call Composables Only in Setup Context Synchronously
impact: HIGH
impactDescription: Composables called outside setup context or asynchronously fail to register lifecycle hooks and may cause memory leaks
type: gotcha
tags: [vue3, composables, composition-api, setup, async, lifecycle]
---
# Call Composables Only in Setup Context Synchronously
**Impact: HIGH** - Composables must be called synchronously within `<script setup>`, the `setup()` function, or lifecycle hooks. Calling composables asynchronously (after await), in callbacks, or outside component context prevents Vue from associating lifecycle hooks with the component instance, causing silent failures.
This is critical because composables often register `onMounted` and `onUnmounted` hooks internally. If called in the wrong context, these hooks are never registered, leading to uninitialized state or memory leaks.
## Task Checklist
- [ ] Call all composables at the top level of `<script setup>` or `setup()`
- [ ] Never call composables inside async callbacks, setTimeout, or Promise.then
- [ ] Never call composables conditionally (if/else) - call unconditionally and handle the condition inside
- [ ] Never call composables inside loops - restructure to call once with array data
- [ ] Exception: Composables CAN be called in lifecycle hooks like `onMounted`
**Incorrect:**
```vue
<script setup>
import { useFetch } from './composables/useFetch'
import { useAuth } from './composables/useAuth'
// WRONG: Composable called after await
const config = await loadConfig()
const { data } = useFetch(config.apiUrl) // Lifecycle hooks won't register!
// WRONG: Composable called conditionally
if (someCondition) {
const { user } = useAuth() // Inconsistent hook registration!
}
// WRONG: Composable called in callback
setTimeout(() => {
const { data } = useFetch('/api/delayed') // No component context!
}, 1000)
// WRONG: Composable called in loop
for (const url of urls) {
const { data } = useFetch(url) // Creates multiple instances incorrectly
}
</script>
```
**Correct:**
```vue
<script setup>
import { ref, onMounted } from 'vue'
import { useFetch } from './composables/useFetch'
import { useAuth } from './composables/useAuth'
// CORRECT: Call composables synchronously at top level
const { user, isAuthenticated } = useAuth()
const apiUrl = ref('/api/default')
const { data, execute } = useFetch(apiUrl)
// Handle async config loading differently
onMounted(async () => {
const config = await loadConfig()
apiUrl.value = config.apiUrl // Update the ref, composable reacts
})
// CORRECT: Handle condition inside, not outside
const showUserData = computed(() => isAuthenticated.value && someCondition)
// CORRECT: For multiple URLs, use a different pattern
const urls = ref(['/api/a', '/api/b', '/api/c'])
const results = ref([])
// Either fetch in onMounted or use a composable designed for arrays
onMounted(async () => {
results.value = await Promise.all(urls.value.map(url => fetch(url)))
})
</script>
```
## Exception: Calling in Lifecycle Hooks
Composables CAN be called inside lifecycle hooks because Vue maintains the component context:
```vue
<script setup>
import { onMounted } from 'vue'
import { useEventListener } from '@vueuse/core'
// CORRECT: Called in lifecycle hook - component context is available
onMounted(() => {
// This works because we're still in the component's execution context
useEventListener(document, 'visibilitychange', handleVisibility)
})
</script>
```
## Special Case: Async Setup in `<script setup>`
Top-level await in `<script setup>` is special - Vue's compiler automatically preserves context:
```vue
<script setup>
import { useFetch } from './composables/useFetch'
// CORRECT: Top-level await in <script setup> preserves context
// Vue compiler handles this specially
const config = await loadConfig()
const { data } = useFetch(config.apiUrl) // This works!
// But nested awaits still break context:
async function initLater() {
await delay(1000)
const { data } = useFetch('/api/late') // WRONG: This won't work!
}
</script>
```
## Why This Matters
When you call a composable, Vue needs to know which component instance to associate it with. This association happens through an internal "current instance" that's only set during synchronous setup execution.
```javascript
// Inside a composable
export function useFetch(url) {
const data = ref(null)
// These need the current component instance!
onMounted(() => { /* ... */ })
onUnmounted(() => { /* cleanup */ })
// If called outside setup context, Vue can't find the instance
// and these hooks are silently ignored
return { data }
}
```
## Reference
- [Vue.js Composables - Usage Restrictions](https://vuejs.org/guide/reusability/composables.html#usage-restrictions)
- [Vue.js Composition API - Setup Context](https://vuejs.org/api/composition-api-setup.html)
@@ -0,0 +1,139 @@
---
title: Follow Composable Naming Convention and Return Pattern
impact: MEDIUM
impactDescription: Inconsistent composable patterns lead to confusing APIs and reactivity issues when destructuring
type: best-practice
tags: [vue3, composables, composition-api, naming, conventions, refs]
---
# Follow Composable Naming Convention and Return Pattern
**Impact: MEDIUM** - Vue composables should follow established conventions: prefix names with "use" and return plain objects containing refs (not reactive objects). Returning reactive objects causes reactivity loss when destructuring, while inconsistent naming makes code harder to understand.
## Task Checklist
- [ ] Name composables with "use" prefix (e.g., `useMouse`, `useFetch`, `useAuth`)
- [ ] Return a plain object containing refs, not a reactive object
- [ ] Allow both destructuring and object-style access
- [ ] Document the returned refs for consumers
**Incorrect:**
```javascript
// WRONG: No "use" prefix - unclear it's a composable
export function mousePosition() {
const x = ref(0)
const y = ref(0)
return { x, y }
}
// WRONG: Returning reactive object - destructuring loses reactivity
export function useMouse() {
const state = reactive({
x: 0,
y: 0
})
// When consumer destructures: const { x, y } = useMouse()
// x and y become plain values, not reactive!
return state
}
// WRONG: Returning single ref directly - inconsistent API
export function useCounter() {
const count = ref(0)
return count // Consumer must use .value everywhere
}
```
**Correct:**
```javascript
// CORRECT: "use" prefix and returns plain object with refs
export function useMouse() {
const x = ref(0)
const y = ref(0)
function update(event) {
x.value = event.pageX
y.value = event.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
// Return plain object containing refs
return { x, y }
}
// Consumer can destructure and keep reactivity
const { x, y } = useMouse()
watch(x, (newX) => console.log('x changed:', newX)) // Works!
// Or use as object if preferred
const mouse = useMouse()
console.log(mouse.x.value)
```
## Using reactive() Wrapper for Auto-Unwrapping
If consumers prefer auto-unwrapping (no `.value`), they can wrap the result:
```javascript
import { reactive } from 'vue'
import { useMouse } from './composables/useMouse'
// Wrapping in reactive() links the refs
const mouse = reactive(useMouse())
// Now access without .value
console.log(mouse.x) // Auto-unwrapped, still reactive
// But DON'T destructure from this!
const { x } = reactive(useMouse()) // WRONG: loses reactivity again
```
## Pattern: Returning Both State and Actions
```javascript
// Composable with state AND methods
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
function decrement() {
count.value--
}
function reset() {
count.value = initialValue
}
// Return all refs and functions in plain object
return {
count,
doubleCount,
increment,
decrement,
reset
}
}
// Usage
const { count, doubleCount, increment, reset } = useCounter(10)
```
## Naming Convention Examples
| Good Name | Bad Name | Reason |
|-----------|----------|--------|
| `useFetch` | `fetch` | Conflicts with native fetch |
| `useAuth` | `authStore` | "Store" implies Pinia/Vuex |
| `useLocalStorage` | `localStorage` | Conflicts with native API |
| `useFormValidation` | `validateForm` | Sounds like a one-shot function |
| `useWindowSize` | `getWindowSize` | "get" implies synchronous getter |
## Reference
- [Vue.js Composables - Conventions and Best Practices](https://vuejs.org/guide/reusability/composables.html#conventions-and-best-practices)
- [Vue.js Composables - Return Values](https://vuejs.org/guide/reusability/composables.html#return-values)
@@ -0,0 +1,182 @@
---
title: Call toValue() Inside watchEffect for Proper Dependency Tracking
impact: HIGH
impactDescription: Calling toValue() outside watchEffect prevents reactive dependency tracking, causing the effect to never re-run
type: gotcha
tags: [vue3, composables, composition-api, watchEffect, toValue, reactivity]
---
# Call toValue() Inside watchEffect for Proper Dependency Tracking
**Impact: HIGH** - When writing composables that accept `MaybeRefOrGetter` arguments, you must call `toValue()` inside the `watchEffect` callback, not outside. If you extract the value before the watchEffect, Vue cannot track the dependency and the effect will never re-run when the source changes.
This is a subtle but critical mistake that leads to composables that work with initial values but never update.
## Task Checklist
- [ ] Always call `toValue()` inside `watchEffect` callbacks, not before
- [ ] Similarly, access `.value` on refs inside watchEffect, not outside
- [ ] For `watch()`, use a getter function that calls `toValue()`
- [ ] Test that composables update when their inputs change
**Incorrect:**
```javascript
import { ref, watchEffect, toValue } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
// WRONG: toValue called outside watchEffect
// This extracts the value ONCE and passes a static string
const urlValue = toValue(url)
watchEffect(async () => {
try {
// urlValue is a static string - no dependency tracked!
const response = await fetch(urlValue)
data.value = await response.json()
} catch (e) {
error.value = e
}
})
return { data, error }
}
// When used like this:
const apiUrl = ref('/api/users')
const { data } = useFetch(apiUrl)
// Later...
apiUrl.value = '/api/products' // useFetch will NOT refetch!
```
**Correct:**
```javascript
import { ref, watchEffect, toValue } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
watchEffect(async () => {
// CORRECT: toValue called INSIDE watchEffect
// Vue tracks this as a dependency
const urlValue = toValue(url)
try {
const response = await fetch(urlValue)
data.value = await response.json()
} catch (e) {
error.value = e
}
})
return { data, error }
}
// Now when used:
const apiUrl = ref('/api/users')
const { data } = useFetch(apiUrl)
// Later...
apiUrl.value = '/api/products' // useFetch WILL refetch!
```
## The Same Applies to Direct Ref Access
```javascript
// WRONG: Accessing .value outside the effect
export function useDebounce(source, delay = 300) {
// This captures the initial value, not a reactive dependency
const initialValue = source.value // or toValue(source)
watchEffect(() => {
// initialValue is static - this only runs once
console.log('Value:', initialValue)
})
}
// CORRECT: Access inside the effect
export function useDebounce(source, delay = 300) {
watchEffect(() => {
// Vue tracks source.value or toValue(source) as dependency
console.log('Value:', toValue(source))
})
}
```
## Pattern: Using watch() with Getter Functions
For `watch()`, wrap `toValue()` in a getter:
```javascript
import { ref, watch, toValue } from 'vue'
export function useLocalStorage(key, defaultValue) {
const data = ref(defaultValue)
// CORRECT: Use getter function with watch
watch(
() => toValue(key), // Getter calls toValue, tracks dependency
(newKey) => {
const stored = localStorage.getItem(newKey)
data.value = stored ? JSON.parse(stored) : defaultValue
},
{ immediate: true }
)
return data
}
```
## Why This Happens
Vue's reactivity tracking works by detecting property accesses during effect execution:
```javascript
watchEffect(() => {
// When this runs, Vue is "recording" what reactive sources are accessed
const value = someRef.value // Vue records: "this effect depends on someRef"
})
// But if you extract the value before:
const value = someRef.value // Vue isn't recording yet
watchEffect(() => {
console.log(value) // Just using a plain JavaScript variable
})
```
`toValue()` works the same way - it accesses `.value` internally, so it must happen during effect execution for tracking to work.
## Quick Checklist for Composable Authors
When accepting `MaybeRefOrGetter` inputs:
1. Store the raw argument (don't call `toValue` during setup)
2. Call `toValue()` inside any reactive context (`watchEffect`, `watch`, `computed`)
3. Test with both static values AND refs that change
```javascript
export function useMyComposable(input) {
// Store raw - don't extract value here
// const value = toValue(input) // WRONG
const result = computed(() => {
// Extract value inside reactive context
return transform(toValue(input)) // CORRECT
})
watchEffect(() => {
// Extract value inside reactive context
doSomething(toValue(input)) // CORRECT
})
return { result }
}
```
## Reference
- [Vue.js Reactivity API - toValue](https://vuejs.org/api/reactivity-utilities.html#tovalue)
- [Vue.js Composables - Accepting Ref Arguments](https://vuejs.org/guide/reusability/composables.html#accepting-reactive-state)
@@ -0,0 +1,120 @@
---
title: Composition API Uses Mutable Reactivity, Not Functional Programming
impact: MEDIUM
impactDescription: Misunderstanding the paradigm leads to incorrect state management patterns
type: gotcha
tags: [vue3, composition-api, reactivity, functional-programming, paradigm]
---
# Composition API Uses Mutable Reactivity, Not Functional Programming
**Impact: MEDIUM** - Despite being function-based, the Composition API follows Vue's mutable, fine-grained reactivity paradigm—NOT functional programming principles. Treating it like a functional paradigm leads to incorrect patterns like unnecessary cloning, immutable-style updates, or avoiding mutation when mutation is the intended pattern.
Vue's Composition API leverages imported functions to organize code, but the underlying model is based on mutable reactive state that Vue tracks and responds to. This is fundamentally different from functional programming with immutability (like Redux reducers).
## Task Checklist
- [ ] Mutate reactive state directly - don't create new objects for every update
- [ ] Don't apply immutability patterns unnecessarily (spreading, Object.assign for updates)
- [ ] Understand that `ref()` and `reactive()` enable mutable state tracking
- [ ] Use Vue's reactivity as intended: direct mutation with automatic tracking
**Incorrect:**
```javascript
import { ref } from 'vue'
const todos = ref([])
// WRONG: Treating Vue like Redux/functional - unnecessary immutability
function addTodo(todo) {
// Creating a new array every time is wasteful in Vue
todos.value = [...todos.value, todo]
}
function updateTodo(id, updates) {
// Unnecessary spread - Vue tracks mutations directly
todos.value = todos.value.map(t =>
t.id === id ? { ...t, ...updates } : t
)
}
const user = ref({ name: 'John', age: 30 })
// WRONG: Creating new object for simple update
function updateName(newName) {
user.value = { ...user.value, name: newName }
}
```
**Correct:**
```javascript
import { ref, reactive } from 'vue'
const todos = ref([])
// CORRECT: Mutate directly - Vue tracks the change
function addTodo(todo) {
todos.value.push(todo) // Direct mutation is the Vue way
}
function updateTodo(id, updates) {
const todo = todos.value.find(t => t.id === id)
if (todo) {
Object.assign(todo, updates) // Direct mutation
}
}
const user = ref({ name: 'John', age: 30 })
// CORRECT: Mutate the property directly
function updateName(newName) {
user.value.name = newName // Vue tracks this!
}
// Or with reactive():
const state = reactive({ name: 'John', age: 30 })
function updateNameReactive(newName) {
state.name = newName // Direct mutation, reactivity preserved
}
```
## When Immutability Patterns Make Sense
```javascript
// Immutability IS appropriate when:
// 1. Replacing the entire state (e.g., from API response)
const users = ref([])
async function fetchUsers() {
users.value = await api.getUsers() // Complete replacement is fine
}
// 2. When you need a snapshot for comparison
const previousState = { ...currentState } // For undo/redo
// 3. When passing data to external libraries expecting immutable data
const chartData = computed(() => [...rawData.value]) // Copy for chart lib
```
## The Vue Mental Model
```javascript
// Vue's reactivity is like a spreadsheet:
// - Cell A1 contains a value (ref)
// - Cell B1 has a formula referencing A1 (computed)
// - Change A1, and B1 automatically updates
const a1 = ref(10)
const b1 = computed(() => a1.value * 2)
// You CHANGE A1 (mutate), you don't create a new A1
a1.value = 20 // b1 automatically becomes 40
// This is fundamentally different from:
// state = reducer(state, action) // Functional/Redux pattern
```
## Reference
- [Composition API FAQ](https://vuejs.org/guide/extras/composition-api-faq.html)
- [Reactivity Fundamentals](https://vuejs.org/guide/essentials/reactivity-fundamentals.html)
@@ -0,0 +1,203 @@
---
title: Top-Level await in script setup Preserves Component Context
impact: HIGH
impactDescription: Misunderstanding async context causes lifecycle hooks and watchers to silently fail
type: gotcha
tags: [vue3, composition-api, script-setup, async, await, suspense]
---
# Top-Level await in script setup Preserves Component Context
**Impact: HIGH** - In `<script setup>`, top-level `await` statements preserve component context (allowing lifecycle hooks and watchers after `await`), but this is a special case. Nested async functions or callbacks lose context, causing lifecycle hooks to silently fail.
Vue's compiler automatically injects context restoration after each top-level await in `<script setup>`. This doesn't apply to `setup()` function or nested async contexts.
## Task Checklist
- [ ] Understand that top-level await in `<script setup>` is specially handled
- [ ] Never register lifecycle hooks in nested async functions
- [ ] Use `<Suspense>` when using async `<script setup>` components
- [ ] In regular `setup()`, never use await before lifecycle hook registration
- [ ] Register hooks synchronously, then do async work inside them
**Top-Level await Works (script setup only):**
```vue
<script setup>
import { ref, onMounted, watch } from 'vue'
// This is TOP-LEVEL await - Vue compiler preserves context
const config = await fetchConfig() // OK!
// These hooks work because Vue restored context
onMounted(() => {
console.log('This will run!') // Works
})
watch(someRef, () => {
console.log('This will track!') // Works
})
// Another top-level await - still OK
const data = await fetchData(config.apiUrl) // OK!
// Still works after multiple awaits
onMounted(() => {
console.log('This also runs!') // Works
})
</script>
<!-- IMPORTANT: Parent must use Suspense -->
<template>
<Suspense>
<AsyncComponent />
</Suspense>
</template>
```
**Nested Async Breaks Context:**
```vue
<script setup>
import { ref, onMounted, watch } from 'vue'
// WRONG: Nested async function - context lost after await
async function initializeData() {
const config = await fetchConfig()
// BUG: This hook will NOT be registered!
// We're no longer in the synchronous setup context
onMounted(() => {
console.log('This will NEVER run!') // Silent failure
})
// BUG: This watcher won't auto-dispose on unmount
watch(someRef, () => {
console.log('Memory leak - not cleaned up!')
})
}
// Calling the async function
initializeData() // Hooks inside won't work!
// WRONG: Callbacks also lose context
setTimeout(async () => {
await delay(100)
onMounted(() => {
console.log('Never runs!') // Silent failure
})
}, 0)
</script>
```
**Correct Patterns:**
```vue
<script setup>
import { ref, onMounted, watch } from 'vue'
const data = ref(null)
const config = ref(null)
// CORRECT: Register hooks synchronously FIRST
onMounted(async () => {
// Then do async work INSIDE the hook
config.value = await fetchConfig()
data.value = await fetchData(config.value.apiUrl)
})
// CORRECT: Watchers registered synchronously
watch(config, async (newConfig) => {
if (newConfig) {
data.value = await fetchData(newConfig.apiUrl)
}
})
// Or use top-level await for initial data
const initialConfig = await fetchConfig() // OK - top level
config.value = initialConfig
onMounted(() => {
console.log('Works!') // Context preserved by compiler
})
</script>
```
**setup() Function (Not script setup):**
```javascript
// In regular setup(), await ALWAYS breaks context
export default {
async setup() {
const data = ref(null)
// WRONG: Hooks after await won't register
const config = await fetchConfig()
onMounted(() => {
console.log('Never runs!') // Silent failure!
})
return { data }
}
}
// CORRECT: Register hooks before any await
export default {
async setup() {
const data = ref(null)
// Register hooks FIRST (synchronous)
onMounted(async () => {
const config = await fetchConfig()
data.value = await fetchData(config)
})
// Now you can await if needed
// But hooks must be registered before this point
return { data }
}
}
```
## Why This Happens
```javascript
// Vue tracks the "current component instance" during setup
// This is like a global variable that gets set and cleared
// During synchronous setup:
function setup() {
currentInstance = this // Vue sets this
onMounted(cb) // Uses currentInstance to register
// After await, JavaScript resumes in a microtask
await something()
// currentInstance is now null or different!
onMounted(cb) // Can't find the instance - silently fails
}
// <script setup> compiler adds restoration:
// After each await, it injects: setCurrentInstance(savedInstance)
```
## Suspense Requirement
```vue
<!-- When using async script setup, parent needs Suspense -->
<template>
<Suspense>
<!-- Async component with top-level await -->
<AsyncChild />
<!-- Optional: Loading state -->
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
</template>
```
## Reference
- [Composition API FAQ - Async Setup](https://vuejs.org/guide/extras/composition-api-faq.html)
- [Composables - Async Without Await](https://antfu.me/posts/async-with-composition-api)
- [Suspense](https://vuejs.org/guide/built-ins/suspense.html)
@@ -0,0 +1,156 @@
---
title: Vue Composition API Runs Once, Unlike React Hooks
impact: MEDIUM
impactDescription: Understanding this difference prevents over-engineering and React patterns that don't apply
type: gotcha
tags: [vue3, composition-api, react-hooks, setup, stale-closure]
---
# Vue Composition API Runs Once, Unlike React Hooks
**Impact: MEDIUM** - Vue's `setup()` or `<script setup>` executes only once per component instance, while React Hooks run on every render. Developers coming from React often apply patterns (dependency arrays, excessive memoization, useCallback) that are unnecessary and counterproductive in Vue.
Understanding this fundamental difference is crucial for writing idiomatic Vue code. Vue's approach eliminates entire categories of bugs (stale closures, exhaustive deps) that plague React applications.
## Task Checklist
- [ ] Don't implement "dependency arrays" - Vue tracks dependencies automatically
- [ ] Don't wrap functions in "useCallback" equivalents - not needed in Vue
- [ ] Don't use "useMemo" patterns - Vue's `computed()` handles this automatically
- [ ] Understand that closures in Vue don't go "stale" like in React
- [ ] Don't worry about "call order" - Vue composables can be conditional
**React Patterns to Avoid in Vue:**
```javascript
// These patterns are UNNECESSARY in Vue - they solve React-specific problems
// WRONG: Trying to implement dependency arrays (React pattern)
watch(
[dep1, dep2, dep3], // Vue tracks deps automatically in watchEffect
() => {
// ...
}
)
// Unless you specifically WANT to control which deps trigger the watcher,
// prefer watchEffect() which auto-tracks
// WRONG: Memoizing callbacks like useCallback
const memoizedHandler = computed(() => {
return () => doSomething(state.value)
})
// In Vue, just define the function normally - no memoization needed
// WRONG: Worrying about stale closures
function useData() {
const data = ref(null)
// In React, this could capture stale 'data' - NOT in Vue!
// Vue refs are always current
const handler = () => {
console.log(data.value) // Always gets current value
}
return { data, handler }
}
```
**Correct Vue Patterns:**
```javascript
import { ref, computed, watchEffect } from 'vue'
// CORRECT: Auto-dependency tracking with watchEffect
const query = ref('')
const filter = ref('all')
watchEffect(() => {
// Vue automatically detects that this depends on query and filter
// No dependency array needed!
fetchResults(query.value, filter.value)
})
// CORRECT: computed() handles memoization automatically
const expensiveResult = computed(() => {
// Only recalculates when dependencies actually change
return heavyComputation(data.value)
})
// CORRECT: Functions don't need memoization
function handleClick() {
count.value++
}
// Just use it directly - no useCallback wrapper needed
// <button @click="handleClick">
// CORRECT: Closures always access current values
const count = ref(0)
const message = ref('')
function logState() {
// This always logs CURRENT values, never stale ones
console.log(`Count: ${count.value}, Message: ${message.value}`)
}
setTimeout(() => {
logState() // Gets current values even if called later
}, 5000)
```
## Vue's Advantages Over React Hooks
```javascript
// 1. No stale closure problems
const count = ref(0)
onMounted(() => {
setInterval(() => {
// In React: would need useRef or deps array to avoid stale value
// In Vue: count.value is always current
console.log(count.value)
}, 1000)
})
// 2. Composables can be conditional
if (featureEnabled) {
const { data } = useSomeFeature() // This is FINE in Vue!
}
// In React: "Hooks cannot be conditional" - not a problem in Vue
// 3. No exhaustive-deps linting headaches
watchEffect(() => {
// Use any reactive values - Vue tracks them all automatically
// No ESLint rule yelling about missing dependencies
doSomething(a.value, b.value, c.value)
})
// 4. Child components don't need memoization by default
// Vue's reactivity system only updates what actually changed
// No need for React.memo() equivalents in most cases
```
## When Vue Patterns Differ
```javascript
// Setup runs once - so initialization happens once
<script setup>
import { ref, onMounted } from 'vue'
// This code runs ONCE when component is created
const data = ref(null)
console.log('Setup running') // Only logs once
onMounted(() => {
console.log('Mounted') // Only logs once
})
// If you need something to run on every reactive change,
// use watch or watchEffect
watchEffect(() => {
// This runs when dependencies change
console.log('Data changed:', data.value)
})
</script>
```
## Reference
- [Composition API FAQ - Relationship with React Hooks](https://vuejs.org/guide/extras/composition-api-faq.html#relationship-with-react-hooks)
- [Reactivity Fundamentals](https://vuejs.org/guide/essentials/reactivity-fundamentals.html)
@@ -0,0 +1,148 @@
---
title: Avoid Mutating Methods on Arrays in Computed Properties
impact: HIGH
impactDescription: Array mutating methods in computed modify source data causing unexpected behavior
type: capability
tags: [vue3, computed, arrays, mutation, sort, reverse]
---
# Avoid Mutating Methods on Arrays in Computed Properties
**Impact: HIGH** - JavaScript array methods like `reverse()`, `sort()`, `splice()`, `push()`, `pop()`, `shift()`, and `unshift()` mutate the original array. Using them directly on reactive arrays inside computed properties will modify your source data, causing unexpected side effects and bugs.
## Task Checklist
- [ ] Always create a copy of arrays before using mutating methods
- [ ] Use spread operator `[...array]` or `slice()` to copy arrays
- [ ] Prefer non-mutating alternatives when available
- [ ] Be aware which array methods mutate vs return new arrays
**Incorrect:**
```vue
<script setup>
import { ref, computed } from 'vue'
const items = ref([3, 1, 4, 1, 5, 9, 2, 6])
const users = ref([
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
])
// BAD: sort() mutates the original array!
const sortedItems = computed(() => {
return items.value.sort((a, b) => a - b)
})
// BAD: reverse() mutates the original array!
const reversedItems = computed(() => {
return items.value.reverse()
})
// BAD: Both arrays now point to the same mutated data
// items.value and sortedItems.value are the SAME array
// items.value and reversedItems.value are the SAME array
// BAD: Chained mutations
const sortedUsers = computed(() => {
return users.value.sort((a, b) => a.age - b.age)
})
</script>
<template>
<!-- Original array is corrupted! -->
<div>Original: {{ items }}</div>
<div>Sorted: {{ sortedItems }}</div>
</template>
```
**Correct:**
```vue
<script setup>
import { ref, computed } from 'vue'
const items = ref([3, 1, 4, 1, 5, 9, 2, 6])
const users = ref([
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
])
// GOOD: Spread operator creates a copy first
const sortedItems = computed(() => {
return [...items.value].sort((a, b) => a - b)
})
// GOOD: slice() also creates a copy
const reversedItems = computed(() => {
return items.value.slice().reverse()
})
// GOOD: Copy before sorting objects
const sortedUsers = computed(() => {
return [...users.value].sort((a, b) => a.age - b.age)
})
// GOOD: Use toSorted() (ES2023) - non-mutating
const sortedItemsModern = computed(() => {
return items.value.toSorted((a, b) => a - b)
})
// GOOD: Use toReversed() (ES2023) - non-mutating
const reversedItemsModern = computed(() => {
return items.value.toReversed()
})
</script>
<template>
<!-- Original array stays intact -->
<div>Original: {{ items }}</div>
<div>Sorted: {{ sortedItems }}</div>
<div>Reversed: {{ reversedItems }}</div>
</template>
```
## Mutating vs Non-Mutating Array Methods
| Mutating (Avoid in Computed) | Non-Mutating (Safe) |
|------------------------------|---------------------|
| `sort()` | `toSorted()` (ES2023) |
| `reverse()` | `toReversed()` (ES2023) |
| `splice()` | `toSpliced()` (ES2023) |
| `push()` | `concat()` |
| `pop()` | `slice(0, -1)` |
| `shift()` | `slice(1)` |
| `unshift()` | `[item, ...array]` |
| `fill()` | `map()` with new values |
## ES2023 Non-Mutating Alternatives
Modern JavaScript (ES2023) provides non-mutating versions of common array methods:
```javascript
// These return NEW arrays, safe for computed properties
const sorted = array.toSorted((a, b) => a - b)
const reversed = array.toReversed()
const spliced = array.toSpliced(1, 2, 'new')
const withReplaced = array.with(0, 'newFirst')
```
## Deep Copy for Nested Arrays
For arrays of objects where you might mutate nested properties:
```javascript
const items = ref([{ name: 'A', values: [1, 2, 3] }])
// Shallow copy - nested arrays still shared
const copied = computed(() => [...items.value])
// Deep copy if you need to mutate nested structures
const deepCopied = computed(() => {
return JSON.parse(JSON.stringify(items.value))
// Or use structuredClone():
// return structuredClone(items.value)
})
```
## Reference
- [Vue.js Computed Properties - Avoid Mutating Computed Value](https://vuejs.org/guide/essentials/computed.html#avoid-mutating-computed-value)
- [MDN Array Methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
@@ -0,0 +1,147 @@
---
title: Ensure All Dependencies Are Accessed in Computed Properties
impact: HIGH
impactDescription: Conditional logic can prevent dependency tracking causing stale computed values
type: capability
tags: [vue3, computed, reactivity, dependency-tracking, gotcha]
---
# Ensure All Dependencies Are Accessed in Computed Properties
**Impact: HIGH** - Vue tracks computed property dependencies by monitoring which reactive properties are accessed during execution. If conditional logic prevents a property from being accessed on the first run, Vue won't track it as a dependency, causing the computed property to not update when that property changes.
This is a subtle but common source of bugs, especially with short-circuit evaluation (`&&`, `||`) and early returns.
## Task Checklist
- [ ] Access all reactive dependencies before any conditional logic
- [ ] Be cautious with short-circuit operators (`&&`, `||`) that may skip property access
- [ ] Store all dependencies in variables at the start of the computed getter
- [ ] Test computed properties with different initial states
**Incorrect:**
```vue
<script setup>
import { ref, computed } from 'vue'
const isEnabled = ref(false)
const data = ref('important data')
// BAD: If isEnabled is false initially, data.value is never accessed
// Vue won't track 'data' as a dependency!
const result = computed(() => {
if (!isEnabled.value) {
return 'disabled'
}
return data.value // This dependency may not be tracked
})
// BAD: Short-circuit prevents second access
const password = ref('')
const confirmPassword = ref('')
const isValid = computed(() => {
// If password is empty, confirmPassword is never accessed
return password.value && password.value === confirmPassword.value
})
// BAD: Early return prevents dependency access
const user = ref(null)
const permissions = ref(['read', 'write'])
const canEdit = computed(() => {
if (!user.value) {
return false // permissions.value never accessed when user is null
}
return permissions.value.includes('write')
})
</script>
```
**Correct:**
```vue
<script setup>
import { ref, computed } from 'vue'
const isEnabled = ref(false)
const data = ref('important data')
// GOOD: Access all dependencies first
const result = computed(() => {
const enabled = isEnabled.value
const currentData = data.value // Always accessed
if (!enabled) {
return 'disabled'
}
return currentData
})
// GOOD: Access both values before comparison
const password = ref('')
const confirmPassword = ref('')
const isValid = computed(() => {
const pwd = password.value
const confirm = confirmPassword.value // Always accessed
return pwd && pwd === confirm
})
// GOOD: Access all reactive sources upfront
const user = ref(null)
const permissions = ref(['read', 'write'])
const canEdit = computed(() => {
const currentUser = user.value
const currentPermissions = permissions.value // Always accessed
if (!currentUser) {
return false
}
return currentPermissions.includes('write')
})
</script>
```
## The Dependency Tracking Mechanism
Vue's reactivity system works by tracking which reactive properties are accessed when a computed property runs:
```javascript
// How Vue tracks dependencies (simplified):
// 1. Start tracking
// 2. Run the getter function
// 3. Record every .value or reactive property access
// 4. Stop tracking
const computed = computed(() => {
// Vue starts tracking here
if (conditionA.value) { // conditionA is tracked
return valueB.value // valueB is ONLY tracked if conditionA is true
}
return 'default' // If conditionA is false, valueB is NOT tracked!
})
```
## Pattern: Destructure All Dependencies First
```javascript
// GOOD PATTERN: Destructure/access everything at the top
const result = computed(() => {
// Access all potential dependencies
const { user, settings, items } = toRefs(store)
const userVal = user.value
const settingsVal = settings.value
const itemsVal = items.value
// Now use conditional logic safely
if (!userVal) return []
if (!settingsVal.enabled) return []
return itemsVal.filter(i => i.active)
})
```
## Reference
- [Vue.js Reactivity in Depth](https://vuejs.org/guide/extras/reactivity-in-depth.html)
- [GitHub Discussion: Dependency collection gotcha with conditionals](https://github.com/vuejs/Discussion/issues/15)
@@ -0,0 +1,159 @@
---
title: Computed Properties Cannot Accept Parameters
impact: MEDIUM
impactDescription: Attempting to pass arguments to computed properties fails or defeats caching
type: capability
tags: [vue3, computed, methods, parameters, common-mistake]
---
# Computed Properties Cannot Accept Parameters
**Impact: MEDIUM** - Computed properties are designed to derive values from reactive state without parameters. Attempting to pass arguments defeats the caching mechanism or causes errors. Use methods or computed properties that return functions instead.
## Task Checklist
- [ ] Use methods when you need to pass parameters
- [ ] Consider if the parameter can be reactive state instead
- [ ] If you must parameterize, understand that returning a function loses caching benefits
- [ ] Prefer method calls in templates for parameterized operations
**Incorrect:**
```vue
<template>
<!-- BAD: Computed properties don't accept parameters like this -->
<p>{{ filteredItems('active') }}</p>
<p>{{ formattedPrice(100, 'USD') }}</p>
</template>
<script setup>
import { ref, computed } from 'vue'
const items = ref([/* ... */])
// BAD: This won't work as expected
// Computed is called once, not per parameter
const filteredItems = computed((status) => { // status will be undefined or previous value
return items.value.filter(i => i.status === status)
})
</script>
```
```vue
<script>
export default {
data() {
return { items: [/* ... */] }
},
computed: {
// BAD: Computed doesn't receive arguments
filteredItems(status) { // 'status' is actually 'this' or undefined
return this.items.filter(i => i.status === status)
}
}
}
</script>
```
**Correct:**
```vue
<template>
<!-- GOOD: Use method for parameterized operations -->
<p>{{ getFilteredItems('active') }}</p>
<p>{{ formatPrice(100, 'USD') }}</p>
<!-- GOOD: Or use computed with reactive filter state -->
<select v-model="statusFilter">
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
<p>{{ filteredItems }}</p>
</template>
<script setup>
import { ref, computed } from 'vue'
const items = ref([/* ... */])
const statusFilter = ref('active')
// GOOD: Method for parameterized operations
function getFilteredItems(status) {
return items.value.filter(i => i.status === status)
}
function formatPrice(amount, currency) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency
}).format(amount)
}
// GOOD: Computed with reactive parameter
const filteredItems = computed(() => {
return items.value.filter(i => i.status === statusFilter.value)
})
</script>
```
## Workaround: Computed Returning a Function
If you need something computed-like with parameters, you can return a function. **However, this defeats the caching benefit:**
```vue
<template>
<p>{{ getItemsByStatus('active') }}</p>
</template>
<script setup>
import { ref, computed } from 'vue'
const items = ref([/* ... */])
// This works but provides NO caching benefit
// The inner function runs every time it's called
const getItemsByStatus = computed(() => {
return (status) => items.value.filter(i => i.status === status)
})
// This is essentially equivalent to just using a method
// Only useful if you need to compose with other computed properties
</script>
```
## When to Use Each Approach
| Scenario | Approach | Caching |
|----------|----------|---------|
| Fixed filter based on reactive state | Computed | Yes |
| Dynamic filter passed as argument | Method | No |
| Filter options from user selection | Computed + reactive param | Yes |
| Formatting with variable parameters | Method | No |
| Composed derivation with argument | Computed returning function | Partial |
## Make Parameters Reactive
The best pattern is often to make the "parameter" a reactive value:
```vue
<script setup>
import { ref, computed } from 'vue'
const items = ref([/* ... */])
// Instead of passing 'status' as a parameter:
const currentStatus = ref('active')
// Make a computed that uses the reactive status
const filteredItems = computed(() => {
return items.value.filter(i => i.status === currentStatus.value)
})
// Change the filter by updating the ref
function filterByStatus(status) {
currentStatus.value = status
}
</script>
```
## Reference
- [Vue.js Computed Properties](https://vuejs.org/guide/essentials/computed.html)
- [Vue.js Methods](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#declaring-methods)
@@ -0,0 +1,107 @@
---
title: Computed Property Getters Must Be Side-Effect Free
impact: HIGH
impactDescription: Side effects in computed getters break reactivity and cause unpredictable behavior
type: efficiency
tags: [vue3, computed, reactivity, side-effects, best-practices]
---
# Computed Property Getters Must Be Side-Effect Free
**Impact: HIGH** - Computed getter functions should only perform pure computation. Side effects in computed getters break Vue's reactivity model and cause bugs that are difficult to trace.
Computed properties are designed to declaratively describe how to derive a value from other reactive state. They are not meant to perform actions or modify state.
## Task Checklist
- [ ] Never mutate other reactive state inside a computed getter
- [ ] Never make async requests or API calls inside a computed getter
- [ ] Never perform DOM mutations inside a computed getter
- [ ] Use watchers for reacting to state changes with side effects
- [ ] Use event handlers for user-triggered actions
**Incorrect:**
```vue
<script setup>
import { ref, computed } from 'vue'
const items = ref([])
const count = ref(0)
const lastFetch = ref(null)
// BAD: Mutates other state
const doubledCount = computed(() => {
count.value++ // Side effect - modifying state!
return count.value * 2
})
// BAD: Makes async request
const userData = computed(async () => {
const response = await fetch('/api/user') // Side effect - API call!
return response.json()
})
// BAD: Modifies DOM
const highlightedItems = computed(() => {
document.title = `${items.value.length} items` // Side effect - DOM mutation!
return items.value.filter(i => i.highlighted)
})
// BAD: Writes to external state
const processedData = computed(() => {
lastFetch.value = new Date() // Side effect - modifying state!
return items.value.map(i => i.name)
})
</script>
```
**Correct:**
```vue
<script setup>
import { ref, computed, watch, onMounted } from 'vue'
const items = ref([])
const count = ref(0)
const userData = ref(null)
// GOOD: Pure computation only
const doubledCount = computed(() => {
return count.value * 2
})
// GOOD: Use lifecycle hook for initial fetch
onMounted(async () => {
const response = await fetch('/api/user')
userData.value = await response.json()
})
// GOOD: Pure filtering
const highlightedItems = computed(() => {
return items.value.filter(i => i.highlighted)
})
// GOOD: Use watcher for side effects
watch(items, (newItems) => {
document.title = `${newItems.length} items`
}, { immediate: true })
// Increment count through event handler, not computed
function increment() {
count.value++
}
</script>
```
## What Counts as a Side Effect
| Side Effect Type | Example | Alternative |
|-----------------|---------|-------------|
| State mutation | `otherRef.value = x` | Use watcher |
| API calls | `fetch()`, `axios()` | Use watcher or lifecycle hook |
| DOM manipulation | `document.title = x` | Use watcher |
| Console logging | `console.log()` | Remove or use watcher |
| Storage access | `localStorage.setItem()` | Use watcher |
| Timer setup | `setTimeout()` | Use lifecycle hook |
## Reference
- [Vue.js Computed Properties - Getters Should Be Side-Effect Free](https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free)
@@ -0,0 +1,160 @@
---
title: Never Mutate Computed Property Return Values
impact: HIGH
impactDescription: Mutating computed values causes silent failures and lost changes
type: capability
tags: [vue3, computed, reactivity, immutability, common-mistake]
---
# Never Mutate Computed Property Return Values
**Impact: HIGH** - The returned value from a computed property is derived state - a temporary snapshot. Mutating this value leads to bugs that are difficult to debug.
**Important:** Mutations DO persist while the computed cache remains valid, but are lost when recomputation occurs. The danger lies in unpredictable cache invalidation timing - any change to the computed's dependencies triggers recomputation, silently discarding your mutations. This makes bugs intermittent and hard to reproduce.
Every time the source state changes, a new snapshot is created. Mutating a snapshot is meaningless because it will be discarded on the next recalculation.
## Task Checklist
- [ ] Treat computed return values as read-only
- [ ] Update the source state instead of the computed value
- [ ] Use writable computed properties if bidirectional binding is needed
- [ ] Avoid array mutating methods (push, pop, splice, reverse, sort) on computed arrays
**Incorrect:**
```vue
<script setup>
import { ref, computed } from 'vue'
const books = ref(['Vue Guide', 'React Handbook'])
const publishedBooks = computed(() => {
return books.value.filter(book => book.includes('Guide'))
})
function addBook() {
// BAD: Mutating computed value - change will be lost!
publishedBooks.value.push('New Book')
}
// BAD: Mutating computed array
const sortedBooks = computed(() => books.value.filter(b => b))
function reverseBooks() {
// BAD: This mutates the computed snapshot
sortedBooks.value.reverse()
}
</script>
```
```vue
<script>
export default {
data() {
return {
author: {
name: 'John',
books: ['Book A', 'Book B']
}
}
},
computed: {
authorBooks() {
return this.author.books
}
},
methods: {
addBook() {
// BAD: Mutating computed value
this.authorBooks.push('New Book')
}
}
}
</script>
```
**Correct:**
```vue
<script setup>
import { ref, computed } from 'vue'
const books = ref(['Vue Guide', 'React Handbook'])
const publishedBooks = computed(() => {
return books.value.filter(book => book.includes('Guide'))
})
function addBook(bookName) {
// GOOD: Update the source state
books.value.push(bookName)
}
// GOOD: Create a copy before mutating for display
const sortedBooks = computed(() => {
return [...books.value].sort() // Spread to create copy before sort
})
const reversedBooks = computed(() => {
return [...books.value].reverse() // Spread to create copy before reverse
})
</script>
```
```vue
<script>
export default {
data() {
return {
author: {
name: 'John',
books: ['Book A', 'Book B']
}
}
},
computed: {
authorBooks() {
return this.author.books
}
},
methods: {
addBook(bookName) {
// GOOD: Update source state
this.author.books.push(bookName)
}
}
}
</script>
```
## Writable Computed for Bidirectional Binding
If you genuinely need to "set" a computed value, use a writable computed property:
```vue
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
// Writable computed with getter and setter
const fullName = computed({
get() {
return `${firstName.value} ${lastName.value}`
},
set(newValue) {
// Update source state based on the new value
const parts = newValue.split(' ')
firstName.value = parts[0] || ''
lastName.value = parts[1] || ''
}
})
// Now this is valid:
fullName.value = 'Jane Smith' // Updates firstName and lastName
</script>
```
## Reference
- [Vue.js Computed Properties - Avoid Mutating Computed Value](https://vuejs.org/guide/essentials/computed.html#avoid-mutating-computed-value)
- [Vue.js Computed Properties - Writable Computed](https://vuejs.org/guide/essentials/computed.html#writable-computed)
@@ -0,0 +1,89 @@
---
title: Configure Vue App Before Calling mount()
impact: HIGH
impactDescription: App configurations after mount() are silently ignored, causing missing plugins and handlers
type: capability
tags: [vue3, createApp, mount, configuration, setup]
---
# Configure Vue App Before Calling mount()
**Impact: HIGH** - Any app configurations applied after `.mount()` is called are silently ignored. This includes error handlers, global components, directives, and plugins, leading to mysterious missing functionality.
The `.mount()` method should always be called after all app configurations and asset registrations are done. This is a critical ordering requirement that, when violated, produces no errors but causes features to silently fail.
## Task Checklist
- [ ] Register all plugins (router, store, etc.) before mount()
- [ ] Configure error handlers before mount()
- [ ] Register global components and directives before mount()
- [ ] Set all `app.config` properties before mount()
- [ ] Call `.mount()` as the final step in app initialization
**Incorrect:**
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
// WRONG: Mounting first, then configuring
app.mount('#app')
// These are silently IGNORED - app is already mounted!
app.use(router)
app.config.errorHandler = (err) => {
console.error('Global error:', err)
}
app.component('GlobalButton', GlobalButton)
```
**Correct:**
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
import GlobalButton from './components/GlobalButton.vue'
const app = createApp(App)
// Configure everything FIRST
app.use(router)
app.use(createPinia())
// Set up error handling
app.config.errorHandler = (err, instance, info) => {
console.error('Global error:', err)
console.log('Component:', instance)
console.log('Error info:', info)
}
// Register global components
app.component('GlobalButton', GlobalButton)
// Mount LAST - after all configuration is complete
app.mount('#app')
```
## Common Mistake: Chaining with Mount
```javascript
// WRONG: Chaining mount in the middle of configuration
createApp(App)
.use(router)
.mount('#app') // Everything after this line is a problem
.use(pinia) // This doesn't even work - mount returns component instance!
// CORRECT: Either complete chain before mount, or use intermediate variable
createApp(App)
.use(router)
.use(pinia)
.component('GlobalButton', GlobalButton)
.mount('#app') // Mount at the very end
```
## Reference
- [Vue.js - Creating a Vue Application](https://vuejs.org/guide/essentials/application.html)
- [Vue.js Application API](https://vuejs.org/api/application.html)
@@ -0,0 +1,212 @@
---
title: Always Declare Emits for Documentation and Validation
impact: MEDIUM
impactDescription: Undeclared emits cause warnings, break TypeScript inference, and prevent event validation
type: best-practice
tags: [vue3, emits, defineEmits, component-events, typescript, documentation]
---
# Always Declare Emits for Documentation and Validation
**Impact: MEDIUM** - Declaring emitted events with `defineEmits()` or the `emits` option is technically optional, but strongly recommended. Without declarations, Vue shows runtime warnings, TypeScript can't infer event types, and you lose the ability to validate event payloads.
Declared emits also serve as self-documentation, making it immediately clear what events a component can emit.
## Task Checklist
- [ ] Use `defineEmits()` in `<script setup>` to declare all events
- [ ] Use `emits` option when not using `<script setup>`
- [ ] Add TypeScript types for event payloads
- [ ] Consider adding validation functions for complex payloads
- [ ] Document the purpose of each event
## The Warning
When you emit without declaring:
```vue
<script setup>
// No defineEmits declaration
function handleClick() {
emit('select', item) // Vue warns in dev mode
}
</script>
```
Vue warns:
```
[Vue warn]: Component emitted event "select" but it is neither declared
in the emits option nor as an "onSelect" prop.
```
## Basic Declaration
**Correct - Array syntax:**
```vue
<script setup>
const emit = defineEmits(['submit', 'cancel', 'update'])
function handleSubmit() {
emit('submit', formData)
}
function handleCancel() {
emit('cancel')
}
</script>
```
**Correct - Options API:**
```js
export default {
emits: ['submit', 'cancel', 'update'],
methods: {
handleSubmit() {
this.$emit('submit', this.formData)
}
}
}
```
## TypeScript Typed Emits
**Correct - Type-based declaration (recommended for TypeScript):**
```vue
<script setup lang="ts">
interface User {
id: number
name: string
}
const emit = defineEmits<{
submit: [data: FormData]
cancel: []
'update:modelValue': [value: string]
select: [user: User, index: number]
}>()
// Now TypeScript enforces correct payloads
emit('submit', formData) // OK
emit('submit') // Error: Expected 1 argument
emit('select', user) // Error: Expected 2 arguments
emit('unknown') // Error: Unknown event
</script>
```
**Alternative syntax (Vue 3.3+):**
```vue
<script setup lang="ts">
const emit = defineEmits<{
(e: 'submit', data: FormData): void
(e: 'cancel'): void
(e: 'update:modelValue', value: string): void
}>()
</script>
```
## Event Validation
You can validate event payloads at runtime:
**Correct - Validation functions:**
```vue
<script setup>
const emit = defineEmits({
// No validation, just declaration
cancel: null,
// Validate payload
submit: (payload) => {
if (!payload.email) {
console.warn('Submit event requires email')
return false
}
return true
},
// Validate with type checking
click: (id) => typeof id === 'number'
})
</script>
```
Returning `false` from a validator logs a console warning but doesn't prevent the event from being emitted.
## Benefits of Declaring Emits
### 1. Fallthrough Attribute Separation
Without declaration, native event listeners fall through to the root element:
```vue
<!-- ParentComponent.vue -->
<ChildComponent @click="handleClick" />
```
```vue
<!-- ChildComponent.vue - WITHOUT emits declaration -->
<template>
<!-- Native click listener falls through to button -->
<button>Click me</button>
</template>
```
With declaration, Vue knows it's a component event:
```vue
<script setup>
// Now Vue knows 'click' is a component event, not native
const emit = defineEmits(['click'])
</script>
```
### 2. Self-Documentation
```vue
<script setup>
// Clear contract: this component emits these events
const emit = defineEmits<{
'row-click': [row: TableRow]
'row-select': [row: TableRow, selected: boolean]
'page-change': [page: number]
'sort-change': [column: string, direction: 'asc' | 'desc']
}>()
</script>
```
### 3. IDE Support
With declarations, your IDE can:
- Autocomplete event names when using the component
- Show event payload types
- Warn about typos in event names
- Navigate to event definitions
## $emit in Template vs emit in Script
```vue
<script setup>
// $emit is available in template, but...
// emit() is needed in <script setup>
const emit = defineEmits(['submit'])
function handleSubmit() {
// $emit doesn't work here - use emit()
emit('submit', data)
}
</script>
<template>
<!-- $emit works in template -->
<button @click="$emit('submit', data)">Submit</button>
<!-- Or use the declared emit function -->
<button @click="emit('submit', data)">Submit</button>
</template>
```
## Reference
- [Vue.js Component Events - Declaring Emitted Events](https://vuejs.org/guide/components/events.html#declaring-emitted-events)
- [Vue.js Component Events - Events Validation](https://vuejs.org/guide/components/events.html#events-validation)
- [Vue 3 Migration - emits Option](https://v3-migration.vuejs.org/breaking-changes/emits-option)
@@ -0,0 +1,192 @@
---
title: defineExpose Must Be Called Before Any Await
impact: HIGH
impactDescription: Properties exposed after await are inaccessible to parent component refs
type: gotcha
tags: [vue3, script-setup, defineExpose, async, component-refs]
---
# defineExpose Must Be Called Before Any Await
**Impact: HIGH** - In `<script setup>`, if you call `defineExpose()` after an `await` statement, the exposed properties will NOT be accessible to parent components using template refs. This is a subtle async timing issue that causes silent failures.
The compiler transforms top-level await, and code after await runs in a different execution context where defineExpose cannot properly register with the component instance.
## Task Checklist
- [ ] Always call defineExpose() at the top of script setup, before any await
- [ ] If async data is needed in exposed methods, fetch it separately
- [ ] Structure code so expose declarations come first
- [ ] Test parent ref access when using async setup
**Incorrect:**
```vue
<!-- ChildComponent.vue -->
<script setup>
import { ref } from 'vue'
const data = ref(null)
const count = ref(0)
function increment() {
count.value++
}
// WRONG: await before defineExpose
const response = await fetch('/api/data')
data.value = await response.json()
// BROKEN: This won't work - called after await!
defineExpose({
count,
increment,
data
})
</script>
<template>
<div>{{ data }}</div>
</template>
```
```vue
<!-- ParentComponent.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)
onMounted(() => {
// FAILS: All exposed properties are undefined!
console.log(childRef.value.count) // undefined
childRef.value.increment() // TypeError
})
</script>
<template>
<Suspense>
<ChildComponent ref="childRef" />
</Suspense>
</template>
```
**Correct:**
```vue
<!-- ChildComponent.vue -->
<script setup>
import { ref } from 'vue'
const data = ref(null)
const count = ref(0)
function increment() {
count.value++
}
// CORRECT: defineExpose BEFORE any await
defineExpose({
count,
increment,
data
})
// Now safe to use await
const response = await fetch('/api/data')
data.value = await response.json()
</script>
<template>
<div>{{ data }}</div>
</template>
```
```vue
<!-- Alternative: Separate async logic from expose -->
<script setup>
import { ref, onMounted } from 'vue'
const data = ref(null)
const loading = ref(true)
function getData() {
return data.value
}
async function refreshData() {
loading.value = true
const response = await fetch('/api/data')
data.value = await response.json()
loading.value = false
}
// CORRECT: No await at top level - defineExpose always works
defineExpose({
data,
getData,
refreshData,
loading
})
// Trigger async load in lifecycle hook instead
onMounted(() => {
refreshData()
})
</script>
<template>
<div v-if="loading">Loading...</div>
<div v-else>{{ data }}</div>
</template>
```
```vue
<!-- If you must use top-level await, define expose first -->
<script setup>
import { ref } from 'vue'
const user = ref(null)
const posts = ref([])
// CORRECT: All expose calls come first
defineExpose({
user,
posts,
refresh: () => loadData()
})
// Now safe to await
async function loadData() {
const [userRes, postsRes] = await Promise.all([
fetch('/api/user'),
fetch('/api/posts')
])
user.value = await userRes.json()
posts.value = await postsRes.json()
}
// Top-level await after defineExpose is safe
await loadData()
</script>
```
## Why This Happens
Vue's compiler transforms `<script setup>` with top-level await into an async setup function. The component instance context is only available synchronously before the first await. After await, the execution resumes outside that context, making defineExpose ineffective.
```javascript
// What the compiler roughly generates:
async setup() {
const count = ref(0)
// Context available here
await fetch(...) // Suspends execution
// Context lost after resuming
defineExpose({ count }) // Too late!
}
```
## Reference
- [Vue.js Script Setup - defineExpose](https://vuejs.org/api/sfc-script-setup.html#defineexpose)
- [Vue.js Async Components](https://vuejs.org/guide/components/async.html)
@@ -0,0 +1,139 @@
---
title: defineModel Default Value Can Cause Parent-Child Desync
impact: HIGH
impactDescription: Default values in defineModel don't sync back to parent, causing state inconsistency
type: capability
tags: [vue3, v-model, defineModel, components, props, two-way-binding]
---
# defineModel Default Value Can Cause Parent-Child Desync
**Impact: HIGH** - When using `defineModel()` with a default value and the parent doesn't provide a value, the parent and child components will have different values. The parent's ref stays `undefined` while the child uses the default, breaking the two-way binding contract.
This subtle bug can cause confusing behavior where the parent component shows one value while the child shows another, and updates may not propagate correctly.
## Task Checklist
- [ ] Always provide initial values from the parent when using v-model
- [ ] Don't rely on defineModel defaults as the primary source of truth
- [ ] If defaults are needed, also set them in the parent component
- [ ] Test components with and without v-model props provided
**Problem - Parent and child out of sync:**
```html
<!-- ChildComponent.vue -->
<script setup>
// Default value of 1 if parent doesn't provide value
const model = defineModel({ default: 1 })
</script>
<template>
<input v-model="model" type="number">
<!-- Shows: 1 (from default) -->
</template>
```
```html
<!-- ParentComponent.vue -->
<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
// PROBLEM: Parent ref is undefined, not synced with child's default
const myValue = ref() // undefined
</script>
<template>
<ChildComponent v-model="myValue" />
<!-- DESYNC: Child shows 1, but parent shows undefined -->
<p>Parent value: {{ myValue }}</p> <!-- Shows: undefined -->
<!-- Even after child changes value, parent may not update correctly -->
</template>
```
**Solution 1 - Always provide initial value from parent:**
```html
<!-- ParentComponent.vue -->
<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
// CORRECT: Parent provides the initial value
const myValue = ref(1) // Match the expected default
</script>
<template>
<ChildComponent v-model="myValue" />
<p>Parent value: {{ myValue }}</p> <!-- Shows: 1, stays in sync -->
</template>
```
**Solution 2 - Child emits default on mount (if parent control not possible):**
```html
<!-- ChildComponent.vue -->
<script setup>
import { onMounted } from 'vue'
const model = defineModel({ default: 1 })
// Sync default value back to parent on mount
onMounted(() => {
if (model.value === 1) { // Is using default
// Force emit to sync parent
model.value = 1
}
})
</script>
<template>
<input v-model="model" type="number">
</template>
```
**Solution 3 - Use required prop or explicit undefined handling:**
```html
<!-- ChildComponent.vue -->
<script setup>
import { computed } from 'vue'
// Mark as required - TypeScript will warn if not provided
const model = defineModel({ required: true })
// Or handle undefined explicitly
const safeModel = computed({
get: () => model.value ?? 1, // Provide fallback
set: (val) => { model.value = val }
})
</script>
<template>
<input v-model="safeModel" type="number">
</template>
```
**Best Practice - Document expected initial values:**
```html
<!-- ChildComponent.vue -->
<script setup>
/**
* @prop modelValue - The numeric value (parent should initialize to 1 or desired default)
*/
const model = defineModel({
type: Number,
default: 1,
// Adding validator helps catch issues in development
validator: (value) => {
if (value === undefined) {
console.warn('ChildComponent: v-model value is undefined. Provide initial value from parent.')
}
return true
}
})
</script>
```
## Reference
- [Vue.js Component v-model](https://vuejs.org/guide/components/v-model.html)
- [Vue School - defineModel Guide](https://vueschool.io/articles/vuejs-tutorials/v-model-and-definemodel-a-comprehensive-guide-to-two-way-binding-in-vue-js-3/)
@@ -0,0 +1,164 @@
---
title: defineEmits Must Be Used at Top Level of script setup
impact: HIGH
impactDescription: Using defineEmits inside functions causes compilation errors - macros must be at module scope
type: gotcha
tags: [vue3, defineEmits, script-setup, macros, composition-api]
---
# defineEmits Must Be Used at Top Level of script setup
**Impact: HIGH** - The `defineEmits()` macro can only be used directly within `<script setup>` at the top level. It cannot be placed inside functions, conditionals, or any other nested scope. Vue's compiler hoists these macros to module scope during compilation.
This applies to all Vue macros: `defineProps`, `defineEmits`, `defineExpose`, `defineOptions`, and `defineSlots`.
## Task Checklist
- [ ] Place `defineEmits()` directly in `<script setup>`, not inside functions
- [ ] Do not wrap macro calls in conditionals or loops
- [ ] Do not reference local variables in macro arguments
- [ ] Store the emit function and reuse it throughout the component
## The Problem
**Incorrect - Inside a function:**
```vue
<script setup>
function useEvents() {
// ERROR: defineEmits cannot be used inside a function
const emit = defineEmits(['submit', 'cancel'])
return emit
}
const emit = useEvents() // This fails at compile time
</script>
```
**Incorrect - Inside a conditional:**
```vue
<script setup>
if (someCondition) {
// ERROR: Cannot use defineEmits in conditional
const emit = defineEmits(['eventA'])
} else {
const emit = defineEmits(['eventB'])
}
</script>
```
**Incorrect - Referencing local variables:**
```vue
<script setup>
const eventNames = ['submit', 'cancel']
// ERROR: Cannot reference local variables
const emit = defineEmits(eventNames)
</script>
```
## Correct Usage
**Correct - Top level declaration:**
```vue
<script setup>
// CORRECT: defineEmits at top level of script setup
const emit = defineEmits(['submit', 'cancel', 'update'])
function handleSubmit() {
emit('submit', data)
}
function handleCancel() {
emit('cancel')
}
</script>
```
**Correct - With TypeScript types:**
```vue
<script setup lang="ts">
// CORRECT: Type-based declaration at top level
const emit = defineEmits<{
submit: [data: FormData]
cancel: []
'update:modelValue': [value: string]
}>()
function handleSubmit(data: FormData) {
emit('submit', data)
}
</script>
```
**Correct - Using constant arrays (compile-time constant):**
```vue
<script setup>
// CORRECT: Literal array is fine
const emit = defineEmits(['submit', 'cancel'])
</script>
```
## Why This Restriction Exists
Vue's compiler processes `<script setup>` macros at compile time, not runtime. The arguments must be statically analyzable so Vue can:
1. Generate the correct component options
2. Provide TypeScript type inference
3. Enable IDE support for event autocompletion
4. Validate emitted events
Since the macro is hoisted out of `<script setup>` during compilation, it cannot access anything that only exists at runtime.
## Using emit in Composables
If you want to share emit logic in a composable, pass the emit function as an argument:
**Correct - Pass emit to composable:**
```vue
<script setup>
const emit = defineEmits(['submit', 'cancel', 'validate'])
// Pass emit to composable
const { handleSubmit, handleCancel } = useFormEvents(emit)
</script>
```
```js
// composables/useFormEvents.js
export function useFormEvents(emit) {
function handleSubmit(data) {
emit('submit', data)
}
function handleCancel() {
emit('cancel')
}
return { handleSubmit, handleCancel }
}
```
## ESLint Rule
The `eslint-plugin-vue` provides the `vue/valid-define-emits` rule that catches these errors:
```js
// eslint.config.js
export default [
{
rules: {
'vue/valid-define-emits': 'error'
}
}
]
```
This rule reports:
- `defineEmits` used inside functions
- `defineEmits` referencing local variables
- Multiple `defineEmits` calls in the same component
- `defineEmits` used outside `<script setup>`
## Reference
- [Vue.js SFC script setup](https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits)
- [ESLint vue/valid-define-emits](https://eslint.vuejs.org/rules/valid-define-emits)
@@ -0,0 +1,170 @@
---
title: Cannot Mix Runtime and Type Declarations in defineEmits
impact: HIGH
impactDescription: Using both array/object syntax AND TypeScript generics in defineEmits causes compile errors
type: gotcha
tags: [vue3, defineEmits, typescript, compilation-error, script-setup]
---
# Cannot Mix Runtime and Type Declarations in defineEmits
**Impact: HIGH** - `defineEmits` supports two declaration styles: runtime (array/object syntax) and type-based (TypeScript generics). You CANNOT use both at the same time. Attempting to do so results in a compile-time error.
This is a common mistake when learning Vue 3 with TypeScript.
## Task Checklist
- [ ] Choose ONE declaration style: runtime OR type-based
- [ ] For TypeScript projects, prefer type-based declaration
- [ ] For JavaScript projects, use runtime (array/object) declaration
- [ ] Never pass arguments when using generic type parameter
## The Problem
**Incorrect - Mixing both styles:**
```vue
<script setup lang="ts">
// ERROR: Cannot use both type argument and runtime argument
const emit = defineEmits<{
submit: [data: FormData]
}>(['submit']) // This array argument causes the error!
</script>
```
**Compiler error:**
```
defineEmits() cannot accept both type and non-type arguments at the same time.
Use one or the other.
```
**Also incorrect:**
```vue
<script setup lang="ts">
// ERROR: Same problem with object syntax
const emit = defineEmits<{
submit: [data: FormData]
}>({
submit: (data) => !!data
})
</script>
```
## Correct: Type-Based Declaration (TypeScript)
```vue
<script setup lang="ts">
// CORRECT: Type argument only, no runtime argument
const emit = defineEmits<{
submit: [data: FormData]
cancel: []
'update:modelValue': [value: string]
}>()
emit('submit', formData) // TypeScript validates this
emit('cancel')
emit('unknown') // TypeScript error: unknown event
</script>
```
**Alternative call signature syntax:**
```vue
<script setup lang="ts">
const emit = defineEmits<{
(e: 'submit', data: FormData): void
(e: 'cancel'): void
(e: 'update:modelValue', value: string): void
}>()
</script>
```
## Correct: Runtime Declaration (JavaScript or Simple Cases)
**Array syntax:**
```vue
<script setup>
// CORRECT: Runtime array, no type argument
const emit = defineEmits(['submit', 'cancel', 'update:modelValue'])
emit('submit', formData)
emit('cancel')
</script>
```
**Object syntax with validation:**
```vue
<script setup>
// CORRECT: Runtime object for validation
const emit = defineEmits({
submit: (data) => {
if (!data?.email) {
console.warn('Missing email')
return false
}
return true
},
cancel: null // No validation
})
</script>
```
## Adding Validation to Type-Based Emits
If you want TypeScript types AND runtime validation, define the validator separately:
```vue
<script setup lang="ts">
interface FormData {
email: string
message: string
}
// Type-based declaration for TypeScript
const emit = defineEmits<{
submit: [data: FormData]
}>()
// Separate validation function
function emitSubmit(data: FormData) {
if (!data.email.includes('@')) {
console.warn('Invalid email format')
return
}
emit('submit', data)
}
</script>
<template>
<button @click="emitSubmit(formData)">Submit</button>
</template>
```
## Choosing Between Styles
| Style | Use When | Benefits |
|-------|----------|----------|
| Type-based | TypeScript project | Compile-time checking, IDE support |
| Array | JavaScript, simple events | Simple, no types needed |
| Object | Need runtime validation | Validates payloads at runtime |
**Recommendation:** In TypeScript projects, use type-based declaration. It provides the best developer experience with autocompletion and type checking.
## Same Rule Applies to defineProps
This restriction also applies to `defineProps`:
```vue
<script setup lang="ts">
// ERROR: Cannot mix
const props = defineProps<{ name: string }>({ name: String })
// CORRECT: Type-based only
const props = defineProps<{ name: string }>()
// CORRECT: Runtime only
const props = defineProps({ name: String })
</script>
```
## Reference
- [Vue.js SFC script setup - defineEmits](https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits)
- [Vue.js TypeScript with Composition API](https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits)
@@ -0,0 +1,148 @@
---
title: defineModel Object Properties Must Be Replaced, Not Mutated
impact: HIGH
impactDescription: Mutating object properties via defineModel doesn't emit update events, breaking parent sync
type: gotcha
tags: [vue3, v-model, defineModel, objects, reactivity, two-way-binding]
---
# defineModel Object Properties Must Be Replaced, Not Mutated
**Impact: HIGH** - When using `defineModel()` with objects or arrays, directly mutating nested properties like `model.value.prop = x` does NOT emit the `update:modelValue` event. The parent component never receives the change notification, causing silent sync failures.
This happens because Vue only detects when the `model.value` reference itself changes, not when properties of the object are mutated in place.
## Task Checklist
- [ ] Never mutate object properties directly: `model.value.prop = x`
- [ ] Always create a new object reference when updating: `model.value = {...model.value, prop: x}`
- [ ] For arrays, use spread or slice: `model.value = [...model.value, newItem]`
- [ ] Consider using structuredClone for deeply nested objects
**Incorrect - Mutation without event emission:**
```vue
<script setup>
// Child component with object v-model
const model = defineModel<{ name: string; age: number }>()
function updateName(newName: string) {
// WRONG: This mutates the object in place
// Parent receives NO update:modelValue event!
model.value.name = newName
}
function addToList() {
// WRONG: Push mutates the array
model.value.items.push('new item') // Parent not notified
}
</script>
```
**Correct - Replace object reference to trigger event:**
```vue
<script setup>
const model = defineModel<{ name: string; age: number }>()
function updateName(newName: string) {
// CORRECT: Create new object reference
// This triggers update:modelValue event to parent
model.value = {
...model.value,
name: newName
}
}
function addToList() {
// CORRECT: Create new array reference
model.value = {
...model.value,
items: [...model.value.items, 'new item']
}
}
</script>
```
## Deep Nesting Requires Full Path Replacement
```vue
<script setup>
const model = defineModel<{
user: {
address: {
city: string
}
}
}>()
// WRONG: Deep mutation
model.value.user.address.city = 'New York'
// CORRECT: Replace entire chain
model.value = {
...model.value,
user: {
...model.value.user,
address: {
...model.value.user.address,
city: 'New York'
}
}
}
// ALTERNATIVE: Use structuredClone for complex updates
function updateCity(city: string) {
const updated = structuredClone(model.value)
updated.user.address.city = city
model.value = updated // New reference triggers event
}
</script>
```
## Race Condition Warning with Spread Operator
When multiple updates occur rapidly, earlier changes can be lost:
```vue
<script setup>
const model = defineModel<{ a: string; b: string }>()
// CAUTION: Race condition if called in same tick
function updateBothWrong() {
model.value = { ...model.value, a: 'new-a' } // First update
model.value = { ...model.value, b: 'new-b' } // May use stale model.value!
}
// CORRECT: Batch updates into single assignment
function updateBothCorrect() {
model.value = {
...model.value,
a: 'new-a',
b: 'new-b'
}
}
</script>
```
## Alternative: VueUse's useVModel with Deep Option
For complex objects, consider VueUse:
```vue
<script setup>
import { useVModel } from '@vueuse/core'
const props = defineProps<{ modelValue: { name: string } }>()
const emit = defineEmits(['update:modelValue'])
// Deep tracking with passive updates
const model = useVModel(props, 'modelValue', emit, { deep: true, passive: true })
// Now direct mutations work
model.value.name = 'New Name' // Properly syncs with parent
</script>
```
## Reference
- [Vue.js Component v-model](https://vuejs.org/guide/components/v-model.html)
- [GitHub Discussion: defineModel with objects](https://github.com/orgs/vuejs/discussions/10538)
- [SIMPL Engineering: Vue defineModel Pitfalls](https://engineering.simpl.de/post/vue_definemodel/)
@@ -0,0 +1,90 @@
---
title: Use nextTick() to Wait for DOM Updates
impact: MEDIUM
impactDescription: DOM updates are batched and asynchronous - direct DOM access after state changes sees stale values
type: capability
tags: [vue3, dom, nextTick, reactivity, async]
---
# Use nextTick() to Wait for DOM Updates
**Impact: MEDIUM** - Vue batches DOM updates asynchronously for performance. If you access the DOM immediately after changing reactive state, you'll see the old values. Use `nextTick()` to wait for the DOM to update.
When you modify reactive state, Vue doesn't update the DOM synchronously. Instead, it buffers changes and applies them in the next "tick" of the event loop. This is a performance optimization, but it can cause bugs when you need to read from or manipulate the DOM after state changes.
## Task Checklist
- [ ] Use `await nextTick()` when you need to access updated DOM elements after state changes
- [ ] Use `nextTick()` when measuring DOM elements (heights, widths) after data changes
- [ ] Use `nextTick()` when focusing inputs or scrolling after content updates
- [ ] Consider if you really need DOM access - often you can work with reactive data instead
**Incorrect:**
```javascript
import { ref } from 'vue'
const message = ref('Hello')
const messageEl = ref(null)
function updateMessage() {
message.value = 'Updated!'
// WRONG: DOM still shows "Hello" at this point
console.log(messageEl.value.textContent) // "Hello" - stale!
// WRONG: Scrolling/focusing may not work correctly
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
}
```
**Correct:**
```javascript
import { ref, nextTick } from 'vue'
const message = ref('Hello')
const messageEl = ref(null)
async function updateMessage() {
message.value = 'Updated!'
// CORRECT: Wait for DOM to update
await nextTick()
// Now the DOM is updated
console.log(messageEl.value.textContent) // "Updated!"
// Scrolling and focusing now work correctly
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
}
// Alternative: callback syntax
function updateWithCallback() {
message.value = 'Updated!'
nextTick(() => {
console.log(messageEl.value.textContent) // "Updated!"
})
}
```
```vue
<script setup>
import { ref, nextTick } from 'vue'
const items = ref([])
const listRef = ref(null)
async function addItem() {
items.value.push({ id: Date.now(), text: 'New item' })
await nextTick()
// Now we can safely scroll to the new item
listRef.value.lastElementChild?.scrollIntoView({ behavior: 'smooth' })
}
</script>
```
## Reference
- [Vue.js Reactivity Fundamentals - DOM Update Timing](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#dom-update-timing)
- [Vue.js nextTick API](https://vuejs.org/api/general.html#nexttick)
@@ -0,0 +1,146 @@
---
title: Dynamic Directive Arguments Have Syntax Constraints
impact: MEDIUM
impactDescription: Invalid dynamic arguments cause silent failures or browser compatibility issues
type: capability
tags: [vue3, template, directives, v-bind, v-on, dynamic-arguments]
---
# Dynamic Directive Arguments Have Syntax Constraints
**Impact: MEDIUM** - Dynamic directive arguments (e.g., `:[attributeName]`, `@[eventName]`) have value and syntax constraints that can cause silent failures. In-DOM templates also have case sensitivity issues with browsers lowercasing attribute names.
Dynamic arguments allow runtime determination of which attribute or event to bind, but they have restrictions that differ from static arguments.
## Task Checklist
- [ ] Ensure dynamic arguments evaluate to strings or `null`
- [ ] Avoid spaces and quotes inside dynamic argument brackets
- [ ] Use computed properties for complex dynamic argument expressions
- [ ] In in-DOM templates, use lowercase attribute names or switch to SFCs
- [ ] Use `null` to explicitly remove a binding
**Incorrect:**
```vue
<template>
<!-- ERROR: Spaces and quotes not allowed in dynamic arguments -->
<a :[' foo' + bar]="value">Link</a>
<a :["data-" + name]="value">Link</a>
<!-- WARNING: Non-string values (except null) trigger warnings -->
<a :[123]="value">Link</a>
<a :[someObject]="value">Link</a>
<!-- BUG in in-DOM templates: Browsers lowercase attribute names -->
<!-- This becomes :[someattr] which won't match someAttr -->
<a :[someAttr]="url">Link</a>
</template>
<script setup>
// If component expects someAttr but browser lowercases to someattr
// the binding silently fails
const someAttr = 'href'
</script>
```
**Correct:**
```vue
<template>
<!-- OK: Simple variable reference -->
<a :[attributeName]="url">Link</a>
<!-- OK: Use computed property for complex expressions -->
<a :[dynamicAttr]="value">Link</a>
<!-- OK: null removes the binding -->
<button :[disabledAttr]="isDisabled">Submit</button>
<!-- OK: Dynamic event names -->
<button @[eventName]="handler">Click</button>
<!-- OK: In SFCs, case is preserved -->
<a :[someAttr]="url">Link</a>
</template>
<script setup>
import { ref, computed } from 'vue'
// Simple string variable
const attributeName = ref('href')
const url = ref('https://vuejs.org')
// Complex expression via computed property
const prefix = ref('data')
const name = ref('id')
const dynamicAttr = computed(() => `${prefix.value}-${name.value}`)
// Conditional binding with null
const isDisabled = ref(false)
const disabledAttr = computed(() => isDisabled.value ? 'disabled' : null)
// Dynamic events
const useTouch = ref(false)
const eventName = computed(() => useTouch.value ? 'touchstart' : 'click')
function handler() {
console.log('Event triggered')
}
</script>
```
## In-DOM Template Workaround
When writing templates directly in HTML (not SFCs), use lowercase:
```html
<!-- In-DOM template (index.html) -->
<div id="app">
<!-- Use lowercase to avoid browser issues -->
<a :[attrname]="url">Link</a>
</div>
<script type="module">
import { createApp, ref } from 'vue'
createApp({
setup() {
// Match the lowercase used in template
const attrname = ref('href')
const url = ref('https://vuejs.org')
return { attrname, url }
}
}).mount('#app')
</script>
```
## SFC vs In-DOM Templates
| Feature | SFC (.vue files) | In-DOM (HTML) |
|---------|------------------|---------------|
| Case sensitivity | Preserved | Lowercased by browser |
| Dynamic arguments | Full support | Lowercase only |
| Recommendation | Preferred | Use for progressive enhancement |
## Valid Dynamic Argument Values
```vue
<script setup>
// String values - OK
const attr1 = 'href'
const attr2 = 'data-custom'
// null - OK (removes binding)
const attr3 = null
// undefined - OK (removes binding)
const attr4 = undefined
// Numbers, objects, arrays - WARNING
const attr5 = 123 // Warning: should be string
const attr6 = { foo: 1 } // Warning: should be string
</script>
```
## Reference
- [Vue.js Template Syntax - Dynamic Arguments](https://vuejs.org/guide/essentials/template-syntax.html#dynamic-arguments)
- [Vue.js Template Syntax - Dynamic Argument Value Constraints](https://vuejs.org/guide/essentials/template-syntax.html#dynamic-argument-value-constraints)
@@ -0,0 +1,147 @@
---
title: Use import.meta.glob for Dynamic Component Registration in Vite
impact: MEDIUM
impactDescription: require.context from Webpack doesn't work in Vite projects
type: gotcha
tags: [vue3, component-registration, vite, dynamic-import, migration, webpack]
---
# Use import.meta.glob for Dynamic Component Registration in Vite
**Impact: MEDIUM** - When migrating from Webpack to Vite or starting a new Vite project, the `require.context` pattern for dynamically registering components won't work. Vite uses `import.meta.glob` instead. Using the wrong approach will cause build errors or runtime failures.
## Task Checklist
- [ ] Replace `require.context` with `import.meta.glob` in Vite projects
- [ ] Update component registration patterns when migrating from Vue CLI to Vite
- [ ] Use `{ eager: true }` for synchronous loading when needed
- [ ] Handle async components appropriately with `defineAsyncComponent`
**Incorrect (Webpack pattern - doesn't work in Vite):**
```javascript
// main.js - WRONG for Vite
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// This Webpack-specific API doesn't exist in Vite
const requireComponent = require.context(
'./components/base',
false,
/Base[A-Z]\w+\.vue$/
)
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = fileName
.split('/')
.pop()
.replace(/\.\w+$/, '')
app.component(componentName, componentConfig.default || componentConfig)
})
app.mount('#app')
```
**Correct (Vite pattern):**
```javascript
// main.js - Correct for Vite
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// Vite's glob import - eager loading for synchronous registration
const modules = import.meta.glob('./components/base/Base*.vue', { eager: true })
for (const path in modules) {
// Extract component name from path: './components/base/BaseButton.vue' -> 'BaseButton'
const componentName = path.split('/').pop().replace('.vue', '')
app.component(componentName, modules[path].default)
}
app.mount('#app')
```
## Lazy Loading with Async Components
```javascript
// main.js - Lazy loading variant
import { createApp, defineAsyncComponent } from 'vue'
import App from './App.vue'
const app = createApp(App)
// Without { eager: true }, returns functions that return Promises
const modules = import.meta.glob('./components/base/Base*.vue')
for (const path in modules) {
const componentName = path.split('/').pop().replace('.vue', '')
// Wrap in defineAsyncComponent for lazy loading
app.component(componentName, defineAsyncComponent(modules[path]))
}
app.mount('#app')
```
## Glob Pattern Examples
```javascript
// All .vue files in a directory (not recursive)
import.meta.glob('./components/*.vue', { eager: true })
// All .vue files recursively
import.meta.glob('./components/**/*.vue', { eager: true })
// Specific naming pattern
import.meta.glob('./components/Base*.vue', { eager: true })
// Multiple patterns
import.meta.glob([
'./components/Base*.vue',
'./components/App*.vue'
], { eager: true })
// Exclude patterns
import.meta.glob('./components/**/*.vue', {
eager: true,
ignore: ['**/*.test.vue', '**/*.spec.vue']
})
```
## TypeScript Support
```typescript
// main.ts - with proper typing
import { createApp, Component } from 'vue'
import App from './App.vue'
const app = createApp(App)
const modules = import.meta.glob<{ default: Component }>(
'./components/base/Base*.vue',
{ eager: true }
)
for (const path in modules) {
const componentName = path.split('/').pop()!.replace('.vue', '')
app.component(componentName, modules[path].default)
}
app.mount('#app')
```
## Migration Checklist (Webpack to Vite)
| Webpack | Vite |
|---------|------|
| `require.context(dir, recursive, regex)` | `import.meta.glob(pattern, options)` |
| Synchronous by default | Use `{ eager: true }` for sync |
| `.keys()` returns array | Returns object with paths as keys |
| Returns module directly | Access via `.default` for ES modules |
## Reference
- [Vite - Glob Import](https://vitejs.dev/guide/features.html#glob-import)
- [Vue.js Component Registration](https://vuejs.org/guide/components/registration.html)
@@ -0,0 +1,101 @@
---
title: Event Modifier Order Matters
impact: MEDIUM
impactDescription: Modifier order affects event handling behavior - wrong order causes unexpected propagation or prevention
type: gotcha
tags: [vue3, events, modifiers, v-on, click, form]
---
# Event Modifier Order Matters
**Impact: MEDIUM** - When chaining event modifiers, the order determines behavior because Vue generates code in the same sequence. Using `.prevent.self` vs `.self.prevent` produces different results that can cause subtle bugs in event handling.
## Task Checklist
- [ ] Always consider modifier order when chaining multiple modifiers
- [ ] Use `.prevent.self` to prevent default on element AND children
- [ ] Use `.self.prevent` to prevent default ONLY on the element itself
- [ ] Test event behavior on both the element and its children
**Incorrect:**
```html
<!-- WRONG: Unintended behavior - prevents clicks on children too -->
<template>
<div @click.prevent.self="handleClick">
<button>Child Button</button> <!-- Default also prevented here! -->
</div>
</template>
```
```html
<!-- WRONG: Assuming order doesn't matter -->
<template>
<!-- Developer expects only self clicks to be handled -->
<!-- But .prevent runs first, affecting all clicks -->
<a href="/page" @click.prevent.self="navigate">
<span>Click me</span>
</a>
</template>
```
**Correct:**
```html
<!-- CORRECT: Only prevent default on the element itself -->
<template>
<div @click.self.prevent="handleClick">
<button>Child Button</button> <!-- Default NOT prevented here -->
</div>
</template>
```
```html
<!-- CORRECT: Prevent default on element and children -->
<template>
<form @submit.prevent.self="onSubmit">
<button type="submit">Submit</button>
</form>
</template>
```
```html
<!-- CORRECT: Explicit intent with separate handlers when needed -->
<template>
<div @click.self="handleSelfClick">
<button @click.prevent="handleChildClick">
Child with prevented default
</button>
</div>
</template>
```
## How Modifier Order Works
```javascript
// Vue compiles modifiers in order, so:
// @click.prevent.self compiles to:
// event.preventDefault()
// if (event.target !== event.currentTarget) return
// handler()
// @click.self.prevent compiles to:
// if (event.target !== event.currentTarget) return
// event.preventDefault()
// handler()
```
## Common Modifier Combinations
```html
<!-- Stop propagation AND prevent default -->
<a @click.stop.prevent="handleClick">Link</a>
<!-- Capture mode with once -->
<div @click.capture.once="handleOnce">...</div>
<!-- Only exact modifier key combination -->
<button @click.ctrl.exact="onCtrlClick">Ctrl+Click Only</button>
```
## Reference
- [Vue.js Event Handling - Event Modifiers](https://vuejs.org/guide/essentials/event-handling.html#event-modifiers)
@@ -0,0 +1,155 @@
---
title: Use .exact Modifier for Precise Keyboard/Mouse Shortcuts
impact: MEDIUM
impactDescription: Without .exact, shortcuts fire even when additional modifier keys are pressed, causing unintended behavior
type: best-practice
tags: [vue3, events, keyboard, modifiers, shortcuts, accessibility]
---
# Use .exact Modifier for Precise Keyboard/Mouse Shortcuts
**Impact: MEDIUM** - By default, Vue's modifier key handlers (`.ctrl`, `.alt`, `.shift`, `.meta`) fire even when other modifier keys are also pressed. Use `.exact` to require that ONLY the specified modifiers are pressed, preventing accidental triggering of shortcuts.
## Task Checklist
- [ ] Use `.exact` when you need precise modifier combinations
- [ ] Without `.exact`: `@click.ctrl` fires for Ctrl+Click AND Ctrl+Shift+Click
- [ ] With `.exact`: `@click.ctrl.exact` fires ONLY for Ctrl+Click
- [ ] Use `@click.exact` for plain clicks with no modifiers
**Incorrect:**
```html
<!-- WRONG: Fires even with additional modifiers -->
<template>
<button @click.ctrl="copyItem">Copy</button>
<!-- Also fires on Ctrl+Shift+Click, Ctrl+Alt+Click, etc. -->
<button @click.ctrl.shift="copyAll">Copy All</button>
<!-- User expects Ctrl+Shift, but also fires on Ctrl+Shift+Alt -->
</template>
```
```html
<!-- WRONG: Conflicting shortcuts without .exact -->
<template>
<div>
<button @click.ctrl="copy">Copy (Ctrl+Click)</button>
<button @click.ctrl.shift="copyAll">Copy All (Ctrl+Shift+Click)</button>
<!-- Both fire when user does Ctrl+Shift+Click! -->
</div>
</template>
```
**Correct:**
```html
<!-- CORRECT: Precise modifier matching with .exact -->
<template>
<button @click.ctrl.exact="copyItem">Copy (Ctrl only)</button>
<!-- Only fires on Ctrl+Click, not Ctrl+Shift+Click -->
<button @click.ctrl.shift.exact="copyAll">Copy All (Ctrl+Shift only)</button>
<!-- Only fires on Ctrl+Shift+Click, not Ctrl+Shift+Alt+Click -->
</template>
```
```html
<!-- CORRECT: Plain click without any modifiers -->
<template>
<button @click.exact="selectItem">Select</button>
<!-- Only fires when NO modifier keys are pressed -->
<!-- Ctrl+Click, Shift+Click, etc. will NOT trigger this -->
</template>
```
```html
<!-- CORRECT: Non-conflicting shortcuts -->
<template>
<div class="editor">
<div
@click.exact="selectItem"
@click.ctrl.exact="addToSelection"
@click.shift.exact="extendSelection"
@click.ctrl.shift.exact="selectRange"
>
Click, Ctrl+Click, Shift+Click, or Ctrl+Shift+Click
</div>
</div>
</template>
```
## Behavior Comparison
```javascript
// WITHOUT .exact
@click.ctrl="handler"
// Fires when: Ctrl+Click, Ctrl+Shift+Click, Ctrl+Alt+Click, Ctrl+Shift+Alt+Click
// Does NOT fire: Click (without Ctrl)
// WITH .exact
@click.ctrl.exact="handler"
// Fires when: ONLY Ctrl+Click
// Does NOT fire: Ctrl+Shift+Click, Ctrl+Alt+Click, Click
// ONLY .exact (no other modifiers)
@click.exact="handler"
// Fires when: Plain click with NO modifiers
// Does NOT fire: Ctrl+Click, Shift+Click, Alt+Click
```
## Practical Example: File Browser Selection
```vue
<template>
<ul class="file-list">
<li
v-for="file in files"
:key="file.id"
@click.exact="selectSingle(file)"
@click.ctrl.exact="toggleSelection(file)"
@click.shift.exact="selectRange(file)"
@click.ctrl.shift.exact="addRangeToSelection(file)"
:class="{ selected: isSelected(file) }"
>
{{ file.name }}
</li>
</ul>
</template>
<script setup>
// Each click type has distinct, non-overlapping behavior
function selectSingle(file) {
// Clear selection and select only this file
}
function toggleSelection(file) {
// Add or remove this file from current selection
}
function selectRange(file) {
// Select all files from last selected to this one
}
function addRangeToSelection(file) {
// Add range to existing selection
}
</script>
```
## Keyboard Shortcuts with .exact
```html
<template>
<div
tabindex="0"
@keydown.ctrl.s.exact.prevent="save"
@keydown.ctrl.shift.s.exact.prevent="saveAs"
@keydown.ctrl.z.exact.prevent="undo"
@keydown.ctrl.shift.z.exact.prevent="redo"
>
<!-- Each shortcut is precisely defined -->
</div>
</template>
```
## Reference
- [Vue.js Event Handling - .exact Modifier](https://vuejs.org/guide/essentials/event-handling.html#exact-modifier)
@@ -0,0 +1,159 @@
# Fallthrough Attributes Overwrite Explicit Attributes in Vue 3
## Rule
In Vue 3, fallthrough attributes overwrite explicitly set attributes on the root element (except `class` and `style` which are merged). This is a breaking change from Vue 2. To preserve explicit attribute values, use `inheritAttrs: false` and manually bind `$attrs` before the explicit attribute.
## Why This Matters
- Silent behavior change from Vue 2 to Vue 3
- Can cause unexpected attribute values in migrated codebases
- Only `class` and `style` merge intelligently; other attributes are overwritten
- Affects component composition patterns and wrapper components
## Bad Code
```vue
<!-- Parent.vue -->
<template>
<Child msg="Passed from Parent" />
</template>
<!-- Child.vue - UNEXPECTED BEHAVIOR -->
<template>
<GrandChild msg="Set in Child" />
</template>
<!--
Vue 3 Result: GrandChild receives msg="Passed from Parent"
The fallthrough attribute OVERWRITES the explicit one!
Vue 2 Result: GrandChild receives msg="Set in Child"
The explicit attribute took precedence
-->
```
### Another common case with data attributes
```vue
<!-- Parent.vue -->
<template>
<Button data-testid="parent-button" />
</template>
<!-- Button.vue - WRONG: explicit data-testid is overwritten -->
<template>
<button data-testid="submit-btn">Submit</button>
</template>
<!-- Result: <button data-testid="parent-button">Submit</button> -->
<!-- The component's intended test ID is lost! -->
```
## Good Code
### Option 1: Control attribute order with inheritAttrs: false
```vue
<!-- Child.vue - CORRECT: Control attribute precedence -->
<script setup>
defineOptions({
inheritAttrs: false
})
</script>
<template>
<!-- v-bind="$attrs" FIRST, then explicit attribute -->
<GrandChild v-bind="$attrs" msg="Set in Child" />
</template>
<!--
Result: GrandChild receives msg="Set in Child"
Explicit attribute overrides fallthrough because it comes last
-->
```
### Option 2: Exclude specific attrs from fallthrough
```vue
<script setup>
import { computed, useAttrs } from 'vue'
defineOptions({
inheritAttrs: false
})
const attrs = useAttrs()
// Filter out attributes you want to control explicitly
const filteredAttrs = computed(() => {
const { msg, ...rest } = attrs
return rest
})
</script>
<template>
<GrandChild v-bind="filteredAttrs" msg="Set in Child" />
</template>
```
### Option 3: For wrapper components, declare as prop
```vue
<!-- Button.vue - BEST: Declare attributes you need to control -->
<script setup>
const props = defineProps({
dataTestid: {
type: String,
default: 'submit-btn'
}
})
defineOptions({
inheritAttrs: false
})
</script>
<template>
<button :data-testid="dataTestid" v-bind="$attrs">
<slot />
</button>
</template>
```
## Class and Style Are Special
Unlike other attributes, `class` and `style` merge rather than overwrite:
```vue
<!-- Parent.vue -->
<template>
<Button class="large" style="color: red" />
</template>
<!-- Button.vue -->
<template>
<button class="btn" style="padding: 10px">Submit</button>
</template>
<!--
Result: <button class="btn large" style="padding: 10px; color: red">
Both classes and styles are MERGED, not overwritten
-->
```
## Vue 2 to Vue 3 Migration Checklist
When migrating components that rely on attribute precedence:
1. Identify components that set explicit attributes on root elements
2. Check if parent components pass the same attributes
3. If explicit values should take precedence:
- Add `inheritAttrs: false`
- Use `v-bind="$attrs"` before explicit attributes
## References
- [Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
- [Vue 3 Migration Guide - Attribute Coercion Behavior](https://v3-migration.vuejs.org/breaking-changes/)
- [Vue Fallthrough Attributes behaviour changes from Vue 2 to Vue 3](https://lukes.tips/posts/vue-3-fallthough-attributes-changes/)
@@ -0,0 +1,149 @@
---
title: In-DOM Template Parsing Caveats
impact: HIGH
impactDescription: Browser HTML parsing before Vue compilation causes case sensitivity, self-closing tag, and element nesting issues
type: gotcha
tags: [vue3, templates, in-dom, html-parsing, kebab-case, self-closing-tags]
---
# In-DOM Template Parsing Caveats
**Impact: HIGH** - When writing Vue templates directly in the DOM (not in `.vue` files), the browser's native HTML parser processes the template BEFORE Vue sees it. This causes three critical issues: case sensitivity problems, self-closing tag failures, and element placement restrictions.
These issues do NOT apply to Single-File Components (SFCs) or string templates where Vue's compiler handles parsing directly.
## Task Checklist
- [ ] Use kebab-case for component names in in-DOM templates
- [ ] Use kebab-case for prop names in in-DOM templates
- [ ] Use explicit closing tags (not self-closing) in in-DOM templates
- [ ] Use `is="vue:component-name"` for components inside restricted elements
- [ ] Prefer SFCs to avoid all in-DOM parsing issues
## Issue 1: Case Insensitivity
HTML is case-insensitive. The browser lowercases everything before Vue sees it.
**Incorrect (in-DOM template):**
```html
<!-- Browser converts to: <blogpost posttitle="hello"> -->
<BlogPost postTitle="hello" @updatePost="onUpdate"></BlogPost>
```
**Correct (in-DOM template):**
```html
<!-- Use kebab-case for everything -->
<blog-post post-title="hello" @update-post="onUpdate"></blog-post>
```
**In SFCs, PascalCase works fine:**
```vue
<!-- BlogPost.vue - PascalCase recommended -->
<template>
<BlogPost postTitle="hello" @updatePost="onUpdate" />
</template>
```
## Issue 2: Self-Closing Tags Fail
HTML only allows self-closing syntax for void elements (`<input>`, `<img>`, etc.). For all others, the browser expects closing tags.
**Incorrect (in-DOM template):**
```html
<!-- Browser thinks the tag never closed, breaks nesting -->
<my-component />
<another-component />
```
**Correct (in-DOM template):**
```html
<!-- Explicit closing tags required -->
<my-component></my-component>
<another-component></another-component>
```
**In SFCs, self-closing works fine:**
```vue
<template>
<MyComponent />
<AnotherComponent />
</template>
```
## Issue 3: Element Placement Restrictions
Some HTML elements have strict rules about valid children. Invalid elements are hoisted out by the browser before Vue sees the template.
**Restricted parent elements:**
- `<ul>`, `<ol>` - only allow `<li>`
- `<table>` - only allows `<thead>`, `<tbody>`, `<tfoot>`, `<tr>`, `<caption>`, `<colgroup>`
- `<tr>` - only allows `<td>`, `<th>`
- `<select>` - only allows `<option>`, `<optgroup>`
**Incorrect (in-DOM template):**
```html
<!-- Browser hoists blog-post-row outside the table -->
<table>
<blog-post-row v-for="post in posts" :post="post"></blog-post-row>
</table>
<!-- Renders as: -->
<blog-post-row></blog-post-row>
<blog-post-row></blog-post-row>
<table></table>
```
**Correct (in-DOM template):**
```html
<!-- Use is="vue:component-name" on a valid native element -->
<table>
<tr is="vue:blog-post-row" v-for="post in posts" :key="post.id" :post="post"></tr>
</table>
```
```html
<ul>
<li is="vue:todo-item" v-for="todo in todos" :key="todo.id" :todo="todo"></li>
</ul>
```
**Important:** The `vue:` prefix is required! Without it, `is` is treated as a native customized built-in element attribute.
```html
<!-- WRONG: Missing vue: prefix -->
<tr is="blog-post-row"></tr>
<!-- CORRECT: With vue: prefix -->
<tr is="vue:blog-post-row"></tr>
```
## When Do These Apply?
| Template Type | Affected? | Example |
|---------------|-----------|---------|
| Single-File Component (`.vue`) | No | `<template>` section |
| String template | No | `template: '<div>...</div>'` |
| In-DOM template | **Yes** | `<div id="app">...</div>` |
| `<script type="text/x-template">` | **Yes** | Browser parses the script content |
## Best Practice: Use SFCs
The simplest solution is to use Single-File Components (`.vue` files) which completely avoid in-DOM parsing issues:
```vue
<!-- MyComponent.vue - All issues avoided -->
<script setup>
import BlogPost from './BlogPost.vue'
</script>
<template>
<BlogPost postTitle="hello" @updatePost="onUpdate" />
<table>
<BlogPostRow v-for="post in posts" :key="post.id" :post="post" />
</table>
</template>
```
## Reference
- [Vue.js - In-DOM Template Parsing Caveats](https://vuejs.org/guide/essentials/component-basics.html#in-dom-template-parsing-caveats)
@@ -0,0 +1,230 @@
# Use inheritAttrs: false for Wrapper Components
## Rule
When building wrapper components where attributes should be applied to an inner element instead of the root element, always set `inheritAttrs: false` and explicitly bind `$attrs` to the target element.
## Why This Matters
- By default, Vue applies all non-prop attributes to the root element
- Wrapper components often have a non-semantic root (div wrapper, label wrapper)
- Attributes like `id`, `aria-*`, `data-*`, and event listeners should target the functional element
- Without `inheritAttrs: false`, accessibility and functionality can break
## Bad Code
```vue
<!-- BaseInput.vue - WRONG: attrs go to wrapper div, not input -->
<template>
<div class="input-wrapper">
<label>{{ label }}</label>
<input type="text" />
</div>
</template>
<script setup>
defineProps(['label'])
</script>
<!-- Parent usage -->
<BaseInput
id="email"
placeholder="Enter email"
aria-describedby="email-help"
@focus="handleFocus"
/>
<!--
RESULT: All attrs go to the wrapper div!
<div class="input-wrapper" id="email" placeholder="Enter email" ...>
<label>...</label>
<input type="text" /> <!-- No id, placeholder, or aria! -->
</div>
-->
```
## Good Code
```vue
<!-- BaseInput.vue - CORRECT: attrs bound to input element -->
<script setup>
defineProps(['label'])
defineOptions({
inheritAttrs: false
})
</script>
<template>
<div class="input-wrapper">
<label>{{ label }}</label>
<input type="text" v-bind="$attrs" />
</div>
</template>
<!-- Parent usage -->
<BaseInput
id="email"
placeholder="Enter email"
aria-describedby="email-help"
@focus="handleFocus"
/>
<!--
RESULT: Attrs correctly applied to input
<div class="input-wrapper">
<label>...</label>
<input type="text" id="email" placeholder="Enter email"
aria-describedby="email-help" />
</div>
-->
```
## Setting inheritAttrs in Different Syntaxes
### Script Setup (Vue 3.3+)
```vue
<script setup>
defineOptions({
inheritAttrs: false
})
</script>
```
### Script Setup (Before Vue 3.3)
```vue
<script>
export default {
inheritAttrs: false
}
</script>
<script setup>
// Your setup code here
</script>
```
### Options API
```vue
<script>
export default {
inheritAttrs: false,
// other options...
}
</script>
```
## Common Wrapper Component Patterns
### Form Input Wrapper
```vue
<script setup>
import { useAttrs, computed } from 'vue'
defineProps({
label: String,
error: String
})
defineOptions({
inheritAttrs: false
})
const attrs = useAttrs()
// Separate class/style for wrapper vs input
const inputAttrs = computed(() => {
const { class: _, style: __, ...rest } = attrs
return rest
})
</script>
<template>
<div class="form-field" :class="{ 'has-error': error }">
<label v-if="label">{{ label }}</label>
<input v-bind="inputAttrs" />
<span v-if="error" class="error">{{ error }}</span>
</div>
</template>
```
### Button with Icon Wrapper
```vue
<script setup>
defineProps({
icon: String,
iconPosition: {
type: String,
default: 'left'
}
})
defineOptions({
inheritAttrs: false
})
</script>
<template>
<button class="icon-button" v-bind="$attrs">
<span v-if="icon && iconPosition === 'left'" class="icon">{{ icon }}</span>
<slot />
<span v-if="icon && iconPosition === 'right'" class="icon">{{ icon }}</span>
</button>
</template>
```
### Link Wrapper Component
```vue
<script setup>
defineProps({
to: String,
external: Boolean
})
defineOptions({
inheritAttrs: false
})
</script>
<template>
<a
v-if="external"
:href="to"
target="_blank"
rel="noopener noreferrer"
v-bind="$attrs"
>
<slot />
</a>
<router-link v-else :to="to" v-bind="$attrs">
<slot />
</router-link>
</template>
```
## When NOT to Use inheritAttrs: false
- Simple components with a single semantic root element
- Components where the root element should receive all attributes
- Components that don't wrap other functional elements
```vue
<!-- SimpleCard.vue - No need for inheritAttrs: false -->
<template>
<article class="card">
<slot />
</article>
</template>
<!-- Passing class, id, or data-* to the root article is fine -->
```
## References
- [Fallthrough Attributes - Disabling Attribute Inheritance](https://vuejs.org/guide/components/attrs.html#disabling-attribute-inheritance)
- [Build Advanced Components in Vue 3 using $attrs](https://www.thisdot.co/blog/build-advanced-components-in-vue-3-using-usdattrs)
@@ -0,0 +1,222 @@
---
title: KeepAlive with Nested Routes Double Mount Issue
impact: HIGH
impactDescription: Using KeepAlive with nested Vue Router routes can cause child components to mount twice
type: gotcha
tags: [vue3, keepalive, vue-router, nested-routes, double-mount, bug]
---
# KeepAlive with Nested Routes Double Mount Issue
**Impact: HIGH** - When using `<KeepAlive>` with nested Vue Router routes, child route components may mount twice. This is a known issue that can cause duplicate API calls, broken state, and confusing behavior.
## Task Checklist
- [ ] Test nested routes thoroughly when using KeepAlive
- [ ] Avoid mixing KeepAlive with deeply nested route structures
- [ ] Use workarounds if double mount is observed
- [ ] Consider alternative caching strategies for nested routes
## The Problem
```vue
<!-- App.vue -->
<template>
<router-view v-slot="{ Component }">
<KeepAlive>
<component :is="Component" />
</KeepAlive>
</router-view>
</template>
```
```javascript
// router.js
const routes = [
{
path: '/parent',
component: Parent,
children: [
{
path: 'child',
component: Child // This may mount TWICE!
}
]
}
]
```
**Symptoms:**
- `onMounted` called twice in child component
- Duplicate API requests
- State initialization runs twice
- Console logs appear doubled
## Diagnosis
Add logging to confirm the issue:
```vue
<!-- Child.vue -->
<script setup>
import { onMounted, onActivated } from 'vue'
let mountCount = 0
onMounted(() => {
mountCount++
console.log('Child mounted - count:', mountCount)
// If you see "count: 2", you have the double mount issue
})
onActivated(() => {
console.log('Child activated')
})
</script>
```
## Workarounds
### Option 1: Use `useActivatedRoute` Pattern
Don't use `useRoute()` directly with KeepAlive:
```vue
<script setup>
import { ref, onActivated } from 'vue'
import { useRoute } from 'vue-router'
// Problem: useRoute() can cause issues with KeepAlive
// const route = useRoute()
// Solution: Get route info in onActivated
const routeParams = ref({})
onActivated(() => {
const route = useRoute()
routeParams.value = { ...route.params }
})
</script>
```
### Option 2: Avoid KeepAlive for Nested Route Parents
Only cache leaf routes, not parent layouts:
```vue
<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// Only cache specific leaf routes
const cachedRoutes = computed(() => {
// Don't cache parent routes that have children
return ['UserProfile', 'UserSettings'] // Only leaf components
})
</script>
<template>
<router-view v-slot="{ Component, route: currentRoute }">
<KeepAlive :include="cachedRoutes">
<component :is="Component" :key="currentRoute.fullPath" />
</KeepAlive>
</router-view>
</template>
```
### Option 3: Guard Against Double Initialization
Protect your component from double mount effects:
```vue
<script setup>
import { ref, onMounted } from 'vue'
const isInitialized = ref(false)
onMounted(() => {
if (isInitialized.value) {
console.warn('Double mount detected, skipping initialization')
return
}
isInitialized.value = true
// Safe to initialize
fetchData()
setupEventListeners()
})
</script>
```
### Option 4: Use Route-Level Cache Control
```vue
<!-- App.vue -->
<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// Define which routes should be cached in route meta
const shouldCache = computed(() => {
return route.meta.keepAlive !== false
})
</script>
<template>
<router-view v-slot="{ Component }">
<KeepAlive v-if="shouldCache">
<component :is="Component" />
</KeepAlive>
<component v-else :is="Component" />
</router-view>
</template>
```
```javascript
// router.js
const routes = [
{
path: '/parent',
component: Parent,
meta: { keepAlive: false }, // Don't cache parent routes
children: [
{
path: 'child',
component: Child,
meta: { keepAlive: true } // Cache leaf routes
}
]
}
]
```
### Option 5: Flatten Route Structure
Avoid nesting if possible:
```javascript
// Instead of nested routes
const routes = [
// Flat structure avoids the issue
{ path: '/users', component: UserList },
{ path: '/users/:id', component: UserDetail },
{ path: '/users/:id/settings', component: UserSettings }
]
```
## Key Points
1. **Known Vue Router issue** - Double mount with KeepAlive + nested routes
2. **Watch for symptoms** - Duplicate API calls, doubled logs
3. **Avoid caching parent routes** - Only cache leaf components
4. **Add initialization guards** - Protect against double execution
5. **Test thoroughly** - This issue may not appear immediately
## Reference
- [Vue Router Issue #626: keep-alive in nested route mounted twice](https://github.com/vuejs/router/issues/626)
- [GitHub: vue3-keep-alive-component workaround](https://github.com/emiyalee1005/vue3-keep-alive-component)
- [Vue.js KeepAlive Documentation](https://vuejs.org/guide/built-ins/keep-alive.html)
@@ -0,0 +1,144 @@
---
title: KeepAlive with Transition Memory Leak
impact: MEDIUM
impactDescription: Combining KeepAlive with Transition can cause memory leaks in certain Vue versions
type: gotcha
tags: [vue3, keepalive, transition, memory-leak, animation]
---
# KeepAlive with Transition Memory Leak
**Impact: MEDIUM** - There is a known memory leak when using `<Transition>` and `<KeepAlive>` together. Component instances may not be properly freed from memory when combining these features.
## Task Checklist
- [ ] Test memory behavior when using KeepAlive + Transition together
- [ ] Consider if transition animation is necessary with cached components
- [ ] Use browser DevTools Memory tab to verify no leak
- [ ] Keep Vue updated to get latest bug fixes
## The Problem
```vue
<template>
<!-- Known memory leak combination in some Vue versions -->
<Transition name="fade">
<KeepAlive>
<component :is="currentView" />
</KeepAlive>
</Transition>
</template>
```
When switching between components repeatedly:
- Component instances accumulate in memory
- References prevent garbage collection
- Memory usage grows with each switch
## Diagnosis
Use Chrome DevTools to detect the leak:
1. Open DevTools > Memory tab
2. Take heap snapshot
3. Switch between components 10+ times
4. Take another heap snapshot
5. Compare: look for growing VueComponent count
## Workarounds
### Option 1: Remove Transition if Not Essential
```vue
<template>
<!-- No memory leak without Transition -->
<KeepAlive :max="5">
<component :is="currentView" />
</KeepAlive>
</template>
```
### Option 2: Use CSS Animations Instead
```vue
<template>
<KeepAlive :max="5">
<component
:is="currentView"
:class="{ 'fade-enter': isTransitioning }"
/>
</KeepAlive>
</template>
<style>
.fade-enter {
animation: fadeIn 0.3s ease-in;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
```
### Option 3: Use Strict Cache Limits
If you must use both, minimize impact with strict limits:
```vue
<template>
<Transition name="fade" mode="out-in">
<KeepAlive :max="3">
<component :is="currentView" />
</KeepAlive>
</Transition>
</template>
```
### Option 4: Key-Based Cache Invalidation
Force fresh instances when needed:
```vue
<script setup>
import { ref, computed } from 'vue'
const currentView = ref('Dashboard')
const cacheKey = ref(0)
function switchViewFresh(view) {
currentView.value = view
cacheKey.value++ // Force new instance
}
</script>
<template>
<Transition name="fade" mode="out-in">
<KeepAlive :max="3">
<component :is="currentView" :key="cacheKey" />
</KeepAlive>
</Transition>
</template>
```
## Keep Vue Updated
This is a known issue tracked in Vue's GitHub repository. Memory leak fixes are periodically released, so ensure you're on the latest Vue version:
```bash
npm update vue
```
## Key Points
1. **Known issue** - Memory leaks with KeepAlive + Transition are documented
2. **Test in DevTools** - Use Memory tab to verify your specific usage
3. **Consider alternatives** - CSS animations may work without the leak
4. **Set strict `max`** - Limit cache size to cap memory impact
5. **Keep Vue updated** - Bug fixes are released periodically
## Reference
- [GitHub Issue #9842: Memory leak with transition and keep-alive](https://github.com/vuejs/vue/issues/9842)
- [GitHub Issue #9840: Memory leak with transition and keep-alive](https://github.com/vuejs/vue/issues/9840)
- [Vue.js KeepAlive Documentation](https://vuejs.org/guide/built-ins/keep-alive.html)
@@ -0,0 +1,137 @@
---
title: System Modifier Keys Must Be Held During keyup Events
impact: MEDIUM
impactDescription: Modifier keys (ctrl, alt, shift, meta) behave differently with keyup - they must be held when the key is released
type: gotcha
tags: [vue3, events, keyboard, modifiers, keyup, shortcuts]
---
# System Modifier Keys Must Be Held During keyup Events
**Impact: MEDIUM** - When using system modifier keys (`.ctrl`, `.alt`, `.shift`, `.meta`) with `keyup` events, the modifier must still be pressed when the other key is released. Releasing the modifier key first will not trigger the event, causing keyboard shortcuts to appear broken.
## Task Checklist
- [ ] Understand that `@keyup.ctrl` requires Ctrl to be held while releasing another key
- [ ] Consider using `keydown` instead of `keyup` for modifier key combinations
- [ ] Use `.exact` when you need precise modifier key control
- [ ] Test keyboard shortcuts with proper key release order
**Incorrect:**
```html
<!-- WRONG: Expecting this to fire when Ctrl is released -->
<template>
<input @keyup.ctrl="onCtrlRelease" />
<!-- This does NOT fire when you just release Ctrl! -->
<!-- It fires when you release ANY key while holding Ctrl -->
</template>
```
```html
<!-- WRONG: Misunderstanding keyup.ctrl behavior -->
<template>
<div @keyup.ctrl="handleShortcut">
<!-- User presses Ctrl+S, releases Ctrl first, then S -->
<!-- Event does NOT fire because Ctrl wasn't held during S release -->
</div>
</template>
```
**Correct:**
```html
<!-- CORRECT: User must hold Ctrl while releasing another key -->
<template>
<input @keyup.ctrl.s="saveDocument" />
<!-- User presses Ctrl+S, then releases S while holding Ctrl -->
<!-- Event fires correctly -->
</template>
<script setup>
function saveDocument(event) {
event.preventDefault()
// Save logic here
}
</script>
```
```html
<!-- CORRECT: Use keydown for more intuitive modifier behavior -->
<template>
<div @keydown.ctrl.s="saveDocument">
<!-- keydown fires immediately when both keys are pressed -->
<!-- More intuitive for keyboard shortcuts -->
</div>
</template>
```
```html
<!-- CORRECT: Use .exact for precise modifier control -->
<template>
<!-- Only fires when ONLY Ctrl is pressed (no Shift, Alt, etc.) -->
<button @click.ctrl.exact="onCtrlClick">Ctrl+Click Only</button>
<!-- Fires with no system modifiers at all -->
<button @click.exact="onPlainClick">Plain Click Only</button>
</template>
```
## How System Modifiers Work with keyup
```javascript
// Timeline of Ctrl+S keydown:
// 1. User presses Ctrl (keydown fires)
// 2. User presses S while holding Ctrl (keydown fires)
// Timeline of Ctrl+S keyup:
// 3. User releases S while holding Ctrl (keyup.ctrl.s fires!)
// 4. User releases Ctrl (keyup fires, but not keyup.ctrl.s)
// Common mistake:
// 3. User releases Ctrl first (nothing fires for our handler)
// 4. User releases S (keyup.s fires, but not keyup.ctrl.s)
```
## System Modifier Keys
```html
<!-- Available system modifiers -->
<input @keyup.ctrl="..." /> <!-- Ctrl key -->
<input @keyup.alt="..." /> <!-- Alt key (Option on Mac) -->
<input @keyup.shift="..." /> <!-- Shift key -->
<input @keyup.meta="..." /> <!-- Cmd on Mac, Windows key on PC -->
```
## The .exact Modifier
```html
<!-- Different .exact behaviors -->
<!-- Fires even if Shift/Alt are also pressed -->
<button @click.ctrl="onClick">Ctrl + any other modifiers</button>
<!-- Fires ONLY when Ctrl alone is pressed -->
<button @click.ctrl.exact="onClick">Ctrl only, no other modifiers</button>
<!-- Fires ONLY when no system modifiers are pressed -->
<button @click.exact="onClick">No modifiers allowed</button>
```
## Best Practice: Prefer keydown for Shortcuts
```html
<template>
<div
tabindex="0"
@keydown.ctrl.s.prevent="save"
@keydown.ctrl.z.prevent="undo"
@keydown.ctrl.shift.z.prevent="redo"
>
<!-- keydown is more reliable for keyboard shortcuts -->
<!-- Add .prevent to stop browser default (e.g., save dialog) -->
</div>
</template>
```
## Reference
- [Vue.js Event Handling - Key Modifiers](https://vuejs.org/guide/essentials/event-handling.html#key-modifiers)
- [Vue.js Event Handling - System Modifier Keys](https://vuejs.org/guide/essentials/event-handling.html#system-modifier-keys)
@@ -0,0 +1,216 @@
---
title: Access DOM Only After Mounted Hook
impact: HIGH
impactDescription: Accessing DOM elements before mounted causes undefined errors and silent failures
type: capability
tags: [vue3, vue2, lifecycle, dom, mounted, created, beforeMount, template-refs]
---
# Access DOM Only After Mounted Hook
**Impact: HIGH** - Attempting to access DOM elements or `this.$el` in `created` or `beforeMount` hooks fails because the component's template has not yet been rendered to the DOM. This leads to undefined errors, null references, and failed third-party library initializations.
The component's DOM is only available starting from the `mounted` hook (Options API) or after `onMounted` runs (Composition API). Before this point, `this.$el` is undefined and template refs are null.
## Task Checklist
- [ ] Perform DOM manipulations only in `mounted`/`onMounted` or later
- [ ] Initialize DOM-dependent libraries (charts, maps, editors) in mounted
- [ ] Use `created` for data initialization and API calls (non-DOM operations)
- [ ] Access template refs only after mounted
- [ ] Use `$nextTick` if you need DOM after reactive data changes
**Incorrect:**
```javascript
// WRONG: Accessing DOM in created hook
export default {
created() {
// DOM doesn't exist yet!
console.log(this.$el) // undefined
this.$el.querySelector('.chart') // Error: Cannot read property 'querySelector' of undefined
// Third-party library initialization fails
new Chart(document.getElementById('myChart')) // Element doesn't exist yet
}
}
```
```javascript
// WRONG: Accessing DOM in beforeMount
export default {
beforeMount() {
// Still too early - template is compiled but not mounted
console.log(this.$el) // undefined in Vue 3
this.$refs.myInput.focus() // Error: Cannot read property 'focus' of undefined
}
}
```
```vue
<!-- WRONG: Accessing template ref synchronously in setup -->
<script setup>
import { ref } from 'vue'
const myInput = ref(null)
// This runs during setup, before mounting
myInput.value.focus() // Error: Cannot read property 'focus' of null
</script>
<template>
<input ref="myInput" />
</template>
```
**Correct:**
```javascript
// CORRECT: Use created for data, mounted for DOM
export default {
data() {
return { chartData: null }
},
async created() {
// Data fetching is fine in created
this.chartData = await fetchChartData()
},
mounted() {
// Now the DOM exists and is safe to access
console.log(this.$el) // <div>...</div>
// Initialize DOM-dependent libraries
this.chart = new Chart(this.$refs.chartCanvas, {
data: this.chartData
})
}
}
```
```vue
<!-- CORRECT: Access template refs in onMounted -->
<script setup>
import { ref, onMounted } from 'vue'
const myInput = ref(null)
onMounted(() => {
// DOM is now available
myInput.value.focus() // Works!
})
</script>
<template>
<input ref="myInput" />
</template>
```
```javascript
// CORRECT: Using $nextTick for DOM access after data changes
export default {
methods: {
async addItem() {
this.items.push(newItem)
// Wait for Vue to update the DOM
await this.$nextTick()
// Now the new element exists in DOM
this.$refs.list.lastElementChild.scrollIntoView()
}
}
}
```
## Vue 3 Composition API Pattern
```vue
<script setup>
import { ref, onMounted, nextTick } from 'vue'
const listRef = ref(null)
const items = ref([])
onMounted(() => {
// Safe to access DOM here
listRef.value.style.height = '400px'
})
</script>
```
## Vue 3.5+ useTemplateRef Pattern
```vue
<script setup>
import { useTemplateRef, onMounted } from 'vue'
// Vue 3.5+ recommended approach - decouples ref name from variable name
const input = useTemplateRef('my-input')
onMounted(() => {
input.value.focus()
})
</script>
<template>
<input ref="my-input" />
</template>
```
## Composition API with nextTick
```vue
<script setup>
import { ref, nextTick } from 'vue'
const listRef = ref(null)
const items = ref([])
async function addItem(item) {
items.value.push(item)
// Wait for DOM update after reactive change
await nextTick()
// Now new item is in DOM
listRef.value.lastElementChild.focus()
}
</script>
<template>
<ul ref="listRef">
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
```
## Common Third-Party Libraries
```javascript
// CORRECT: Initialize in mounted
export default {
mounted() {
// Chart.js
this.chart = new Chart(this.$refs.canvas, config)
// Leaflet maps
this.map = L.map(this.$refs.mapContainer).setView([51.505, -0.09], 13)
// Monaco Editor
this.editor = monaco.editor.create(this.$refs.editorContainer, options)
// Video.js
this.player = videojs(this.$refs.videoElement)
},
beforeUnmount() {
// Don't forget cleanup!
this.chart?.destroy()
this.map?.remove()
this.editor?.dispose()
this.player?.dispose()
}
}
```
## Reference
- [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html)
- [Vue.js Template Refs](https://vuejs.org/guide/essentials/template-refs.html)
- [Vue.js nextTick](https://vuejs.org/api/general.html#nexttick)
@@ -0,0 +1,156 @@
---
title: Register Lifecycle Hooks Synchronously During Setup
impact: HIGH
impactDescription: Asynchronously registered lifecycle hooks will never execute
type: capability
tags: [vue3, composition-api, lifecycle, onMounted, onUnmounted, async, setup]
---
# Register Lifecycle Hooks Synchronously During Setup
**Impact: HIGH** - Lifecycle hooks registered asynchronously (e.g., inside setTimeout, after await) will never be called because Vue cannot associate them with the component instance. This leads to silent failures where expected initialization or cleanup code never runs.
In Vue 3's Composition API, lifecycle hooks like `onMounted`, `onUnmounted`, `onUpdated`, etc. must be registered synchronously during component setup. The hook registration doesn't need to be lexically inside `setup()` or `<script setup>`, but the call stack must be synchronous and originate from within setup.
## Task Checklist
- [ ] Register all lifecycle hooks at the top level of setup() or `<script setup>`
- [ ] Never register hooks inside setTimeout, setInterval, or Promise callbacks
- [ ] When calling composables that use lifecycle hooks, call them synchronously
- [ ] Hooks CAN be in external functions if called synchronously from setup
**Incorrect:**
```javascript
// WRONG: Hook registered asynchronously - will NEVER execute
import { onMounted } from 'vue'
export default {
async setup() {
// After await, we're in a different call stack
const data = await fetchInitialData()
// This hook will NOT be registered!
onMounted(() => {
console.log('This will never run')
})
}
}
```
```javascript
// WRONG: Hook registered in setTimeout - will NEVER execute
import { onMounted } from 'vue'
export default {
setup() {
setTimeout(() => {
// This is asynchronous - hook won't be registered!
onMounted(() => {
initializeChart()
})
}, 100)
}
}
```
```javascript
// WRONG: Hook registered in Promise callback
import { onMounted } from 'vue'
export default {
setup() {
fetchConfig().then(() => {
// Asynchronous! This will silently fail
onMounted(() => {
applyConfig()
})
})
}
}
```
**Correct:**
```javascript
// CORRECT: Hook registered synchronously at top level
import { onMounted, ref } from 'vue'
export default {
setup() {
const data = ref(null)
// Register hook synchronously FIRST
onMounted(async () => {
// Async operations are fine INSIDE the hook
data.value = await fetchInitialData()
initializeChart()
})
return { data }
}
}
```
```vue
<!-- CORRECT: <script setup> - hooks at top level -->
<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
const isReady = ref(false)
// These are synchronous during script setup execution
onMounted(() => {
isReady.value = true
})
onUnmounted(() => {
cleanup()
})
</script>
```
```javascript
// CORRECT: Hook in external function called synchronously from setup
import { onMounted, onUnmounted } from 'vue'
function useWindowResize(callback) {
// This is fine - it's called synchronously from setup
onMounted(() => {
window.addEventListener('resize', callback)
})
onUnmounted(() => {
window.removeEventListener('resize', callback)
})
}
export default {
setup() {
// Composable called synchronously - hooks will be registered
useWindowResize(handleResize)
}
}
```
## Multiple Hooks Are Allowed
```javascript
// CORRECT: You can register the same hook multiple times
import { onMounted } from 'vue'
export default {
setup() {
// Both will run, in order of registration
onMounted(() => {
initializeA()
})
onMounted(() => {
initializeB()
})
}
}
```
## Reference
- [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html)
- [Composition API Lifecycle Hooks](https://vuejs.org/api/composition-api-lifecycle.html)
@@ -0,0 +1,184 @@
---
title: Mounted and Unmounted Hooks Do Not Run During SSR
impact: MEDIUM
impactDescription: SSR applications may fail if mounted-only code is essential for functionality
type: capability
tags: [vue3, lifecycle, ssr, server-side-rendering, nuxt, onMounted, mounted, hydration]
---
# Mounted and Unmounted Hooks Do Not Run During SSR
**Impact: MEDIUM** - During server-side rendering (SSR), lifecycle hooks like `mounted`, `onMounted`, `unmounted`, and `onUnmounted` are never called on the server. This can cause differences between server-rendered and client-rendered content, hydration mismatches, and missing functionality if critical logic is placed only in these hooks.
On the server, only `beforeCreate`, `created`, and their Composition API equivalents run. Client-specific operations (DOM access, browser APIs, third-party libraries) must be in mounted hooks, but you must handle the SSR case appropriately.
## Task Checklist
- [ ] Place browser-specific code (window, document, localStorage) in mounted/onMounted
- [ ] Ensure critical data fetching happens in hooks that run on server (created)
- [ ] Handle hydration mismatches for content that differs client vs server
- [ ] Use `<ClientOnly>` wrapper (Nuxt) or conditional rendering for client-only components
- [ ] Check for browser environment before using browser APIs
**Incorrect:**
```javascript
// WRONG: Accessing browser APIs in created - breaks SSR
export default {
created() {
// These don't exist on the server!
this.width = window.innerWidth // ReferenceError: window is not defined
this.savedData = localStorage.getItem('data') // ReferenceError: localStorage is not defined
}
}
```
```javascript
// WRONG: Critical initialization only in mounted - won't run on server
export default {
data() {
return { user: null }
},
async mounted() {
// This won't run on server - page renders without user data
// Then hydrates with user data - causes flash of content
this.user = await fetchCurrentUser()
}
}
```
**Correct:**
```javascript
// CORRECT: Data fetching in created (runs on server), DOM in mounted
export default {
data() {
return {
user: null,
windowWidth: 0
}
},
async created() {
// This runs on both server and client
this.user = await fetchCurrentUser()
},
mounted() {
// Browser-specific code safely in mounted
this.windowWidth = window.innerWidth
window.addEventListener('resize', this.handleResize)
},
unmounted() {
window.removeEventListener('resize', this.handleResize)
}
}
```
```vue
<!-- CORRECT: Composition API with SSR awareness -->
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const user = ref(null)
const windowWidth = ref(0)
// This runs on both server and client (during setup)
user.value = await useFetch('/api/user')
// These only run on client
onMounted(() => {
windowWidth.value = window.innerWidth
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
})
function handleResize() {
windowWidth.value = window.innerWidth
}
</script>
```
## Checking for Browser Environment
```javascript
// CORRECT: Guard browser API access
export default {
data() {
return { theme: 'light' }
},
created() {
// Check if we're in browser before accessing browser APIs
if (typeof window !== 'undefined') {
this.theme = localStorage.getItem('theme') || 'light'
}
},
mounted() {
// mounted only runs in browser, so this is always safe
this.applyTheme()
}
}
```
## Nuxt.js Specific Patterns
```vue
<!-- CORRECT: Using Nuxt's ClientOnly for client-specific components -->
<template>
<div>
<!-- This content renders on both server and client -->
<h1>Dashboard</h1>
<!-- This only renders on client - no hydration mismatch -->
<ClientOnly>
<ChartComponent :data="chartData" />
<template #fallback>
<p>Loading chart...</p>
</template>
</ClientOnly>
</div>
</template>
```
```javascript
// CORRECT: Using Nuxt's process.client/process.server
export default {
created() {
if (process.client) {
// Only runs in browser
this.initAnalytics()
}
if (process.server) {
// Only runs on server
this.logServerRequest()
}
}
}
```
## Handling Hydration Mismatches
```vue
<script setup>
import { ref, onMounted } from 'vue'
// Start with a value that matches what server renders
const currentTime = ref(null)
onMounted(() => {
// Update to real value only on client
// This prevents hydration mismatch
currentTime.value = new Date().toLocaleTimeString()
})
</script>
<template>
<!-- Renders null on server, then updates on client -->
<span v-if="currentTime">{{ currentTime }}</span>
<span v-else>Loading...</span>
</template>
```
## Reference
- [Vue.js SSR Guide](https://vuejs.org/guide/scaling-up/ssr.html)
- [Nuxt.js Lifecycle](https://nuxt.com/docs/api/composables/use-nuxt-app#lifecycle-hooks)
- [Vue SSR Hydration](https://vuejs.org/guide/scaling-up/ssr.html#client-hydration)
@@ -0,0 +1,151 @@
---
title: Locally Registered Components Are Not Available in Descendants
impact: HIGH
impactDescription: Common source of "component not found" errors in nested components
type: gotcha
tags: [vue3, component-registration, local-registration, scope, nested-components]
---
# Locally Registered Components Are Not Available in Descendants
**Impact: HIGH** - Locally registered components are only available in the component where they are registered, NOT in its child or descendant components. This is a common source of "Unknown component" or "Failed to resolve component" errors when developers expect a component registered in a parent to be available in children.
## Task Checklist
- [ ] Import and register components in every file where they are used
- [ ] Do not expect parent's local components to be available in children
- [ ] If a component is needed in many places, consider global registration only as a last resort
- [ ] Use IDE auto-import features to simplify repeated imports
**Incorrect:**
```vue
<!-- ParentComponent.vue -->
<script setup>
import Card from './Card.vue'
import ChildComponent from './ChildComponent.vue'
</script>
<template>
<Card>Parent content</Card>
<ChildComponent />
</template>
```
```vue
<!-- ChildComponent.vue -->
<script setup>
// WRONG: Expecting Card to be available because parent imported it
// This will cause "Failed to resolve component: Card" error
</script>
<template>
<!-- ERROR: Card is not available here! -->
<Card>
Child content
</Card>
</template>
```
**Correct:**
```vue
<!-- ParentComponent.vue -->
<script setup>
import Card from './Card.vue'
import ChildComponent from './ChildComponent.vue'
</script>
<template>
<Card>Parent content</Card>
<ChildComponent />
</template>
```
```vue
<!-- ChildComponent.vue -->
<script setup>
// CORRECT: Each component must import what it uses
import Card from './Card.vue'
</script>
<template>
<Card>
Child content
</Card>
</template>
```
## Common Scenarios
### Scenario 1: Deeply Nested Components
```vue
<!-- GrandchildComponent.vue -->
<script setup>
// Even if parent and grandparent both use Card,
// grandchild must import it separately
import Card from '@/components/Card.vue'
import Button from '@/components/Button.vue'
</script>
<template>
<Card>
<Button>Click me</Button>
</Card>
</template>
```
### Scenario 2: Slot Content with Components
```vue
<!-- Parent.vue -->
<script setup>
import Modal from './Modal.vue'
import Form from './Form.vue'
</script>
<template>
<!-- Form is registered in Parent, so it works in slot content -->
<Modal>
<Form /> <!-- This works because slot content is compiled in Parent's scope -->
</Modal>
</template>
```
```vue
<!-- Modal.vue -->
<script setup>
// Modal doesn't need to import Form because slot content
// is compiled in the parent's scope, not Modal's scope
</script>
<template>
<div class="modal">
<slot /> <!-- Form component works here because it's parent's slot content -->
</div>
</template>
```
### Scenario 3: Dynamic Components
```vue
<!-- Container.vue -->
<script setup>
import TabA from './TabA.vue'
import TabB from './TabB.vue'
import { ref, shallowRef } from 'vue'
// When using dynamic components, all possible components must be imported
const currentTab = shallowRef(TabA)
</script>
<template>
<component :is="currentTab" />
</template>
```
## Why This Design?
Local registration provides:
1. **Explicit dependencies** - You can see exactly what each component uses
2. **Tree-shaking** - Unused components are removed from bundles
3. **Clear scope** - No magic or implicit behavior
## Reference
- [Vue.js Component Registration - Local Registration](https://vuejs.org/guide/components/registration.html#local-registration)
@@ -0,0 +1,88 @@
---
title: mount() Returns Component Instance, Not App Instance
impact: MEDIUM
impactDescription: Using mount() return value for app configuration silently fails
type: capability
tags: [vue3, createApp, mount, api]
---
# mount() Returns Component Instance, Not App Instance
**Impact: MEDIUM** - The `.mount()` method returns the root component instance, not the application instance. Attempting to chain app configuration methods after mount() will fail or produce unexpected behavior.
This is a subtle API detail that catches developers who assume mount() returns the app for continued chaining.
## Task Checklist
- [ ] Never chain app configuration methods after mount()
- [ ] If you need both instances, store them separately
- [ ] Use the component instance for accessing root component state or methods
- [ ] Use the app instance for configuration, plugins, and global registration
**Incorrect:**
```javascript
import { createApp } from 'vue'
import App from './App.vue'
// WRONG: Assuming mount returns app instance
const app = createApp(App).mount('#app')
// This fails! app is actually the root component instance
app.use(router) // TypeError: app.use is not a function
app.config.errorHandler = fn // app.config is undefined
```
```javascript
// WRONG: Trying to save both in one line
const { app, component } = createApp(App).mount('#app') // Doesn't work this way
```
**Correct:**
```javascript
import { createApp } from 'vue'
import App from './App.vue'
// Store app instance separately
const app = createApp(App)
// Configure the app
app.use(router)
app.config.errorHandler = (err) => console.error(err)
// Store component instance if needed
const rootComponent = app.mount('#app')
// Now you have access to both:
// - app: the application instance (for config, plugins)
// - rootComponent: the root component instance (for state, methods)
```
```javascript
// If you only need the app configured and mounted (most common case):
createApp(App)
.use(router)
.use(pinia)
.mount('#app') // Return value (component instance) discarded - that's fine
```
## When You Need the Root Component Instance
```javascript
const app = createApp(App)
const vm = app.mount('#app')
// Access root component's exposed state/methods
console.log(vm.someExposedProperty)
vm.someExposedMethod()
// In Vue 3 with <script setup>, use defineExpose to expose:
// <script setup>
// import { ref } from 'vue'
// const count = ref(0)
// defineExpose({ count })
// </script>
```
## Reference
- [Vue.js - Mounting the App](https://vuejs.org/guide/essentials/application.html#mounting-the-app)
- [Vue.js Application API - mount()](https://vuejs.org/api/application.html#app-mount)
@@ -0,0 +1,93 @@
# Multi-Root Component Class Attribute Inheritance
## Rule
When a Vue 3 component has multiple root elements, class and style bindings from the parent will NOT automatically fall through. You must explicitly bind `$attrs.class` or `$attrs.style` to the target element.
## Why This Matters
- Vue 3 components can have multiple root elements (fragments)
- Unlike single-root components, multi-root components have no automatic attribute fallthrough
- Without explicit handling, classes and styles passed from parent are silently ignored
- Vue will emit a runtime warning, but styles/classes simply won't apply
## Bad Code
```vue
<!-- ChildComponent.vue - WRONG: classes from parent won't apply -->
<template>
<header>Header</header>
<main>Content</main>
<footer>Footer</footer>
</template>
<!-- Parent usage -->
<ChildComponent class="my-custom-class" />
<!-- Result: my-custom-class is NOT applied to any element -->
```
## Good Code
```vue
<!-- ChildComponent.vue - CORRECT: explicitly bind $attrs.class -->
<template>
<header>Header</header>
<main :class="$attrs.class" :style="$attrs.style">Content</main>
<footer>Footer</footer>
</template>
<!-- Or bind all attrs to one element -->
<template>
<header>Header</header>
<main v-bind="$attrs">Content</main>
<footer>Footer</footer>
</template>
```
## Accessing $attrs in script setup
```vue
<script setup>
import { useAttrs } from 'vue'
const attrs = useAttrs()
// attrs.class and attrs.style are available
</script>
<template>
<header>Header</header>
<main :class="attrs.class">Content</main>
<footer>Footer</footer>
</template>
```
## Disabling Automatic Inheritance
For single-root components where you want to control attribute placement:
```vue
<script>
export default {
inheritAttrs: false
}
</script>
<script setup>
import { useAttrs } from 'vue'
const attrs = useAttrs()
</script>
<template>
<div class="wrapper">
<input v-bind="attrs" />
</div>
</template>
```
## Vue 2 to Vue 3 Migration Note
In Vue 2, `$attrs` did NOT include `class` and `style`. In Vue 3, `$attrs` contains ALL attributes including `class` and `style`. This is a breaking change that affects how you handle attribute forwarding.
## References
- [Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
- [Vue 3 Migration Guide - $attrs includes class & style](https://v3-migration.vuejs.org/breaking-changes/attrs-includes-class-style)
@@ -0,0 +1,162 @@
---
title: Declaring Native Event Names in Emits Blocks Native Listeners
impact: MEDIUM
impactDescription: Declaring native events like 'click' in emits prevents native DOM event listeners from working
type: gotcha
tags: [vue3, emits, native-events, click, event-collision]
---
# Declaring Native Event Names in Emits Blocks Native Listeners
**Impact: MEDIUM** - When you declare a native DOM event name (like `click`, `input`, `focus`) in your component's `emits` option, listeners for that event will ONLY respond to your component's `emit()` calls. They will no longer respond to the actual native DOM events on the root element.
This can cause unexpected behavior where clicks seem to stop working on your component.
## Task Checklist
- [ ] Understand that declaring native event names changes listener behavior
- [ ] Always emit the event when you declare it
- [ ] Don't declare native events if you want fallthrough behavior
- [ ] Test click/input handling after adding emits declarations
## The Problem
**Incorrect - Declaring but not emitting:**
```vue
<!-- ClickableCard.vue -->
<script setup>
// Declared 'click' but never emit it!
const emit = defineEmits(['click', 'select'])
</script>
<template>
<div class="card">
<slot></slot>
</div>
</template>
```
```vue
<!-- Parent.vue -->
<template>
<!-- This NEVER fires! Native clicks are blocked -->
<ClickableCard @click="handleClick">
Click me
</ClickableCard>
</template>
```
**Why it fails:**
1. `click` is declared in `emits`
2. Vue treats `@click` as a component event listener
3. Native click on the `<div>` doesn't trigger component event
4. Since `emit('click')` is never called, handler never fires
## The Solution
**Option 1: Emit the event explicitly:**
```vue
<!-- ClickableCard.vue -->
<script setup>
const emit = defineEmits(['click', 'select'])
</script>
<template>
<!-- Explicitly emit click when div is clicked -->
<div class="card" @click="emit('click', $event)">
<slot></slot>
</div>
</template>
```
**Option 2: Don't declare native events (use fallthrough):**
```vue
<!-- ClickableCard.vue -->
<script setup>
// Only declare custom events, not native ones
const emit = defineEmits(['select', 'custom-action'])
</script>
<template>
<!-- Native @click from parent falls through to this div -->
<div class="card">
<slot></slot>
</div>
</template>
```
```vue
<!-- Parent.vue -->
<template>
<!-- Native click falls through and works -->
<ClickableCard @click="handleClick">
Click me
</ClickableCard>
</template>
```
## Native Events Affected
This applies to any native DOM event you might declare:
| Event | Behavior When Declared |
|-------|----------------------|
| `click` | Only responds to `emit('click')`, not native clicks |
| `input` | Only responds to `emit('input')`, not native input |
| `change` | Only responds to `emit('change')`, not native change |
| `focus` | Only responds to `emit('focus')`, not native focus |
| `blur` | Only responds to `emit('blur')`, not native blur |
| `submit` | Only responds to `emit('submit')`, not native form submit |
| `keydown` | Only responds to `emit('keydown')`, not native keydown |
## When This Is Intentional
Sometimes you WANT to intercept native events:
```vue
<!-- CustomInput.vue -->
<script setup>
// Intentionally intercept 'input' to transform the value
const emit = defineEmits(['input', 'update:modelValue'])
function handleInput(event) {
const transformedValue = event.target.value.toUpperCase()
emit('input', transformedValue) // Emit transformed value, not raw event
emit('update:modelValue', transformedValue)
}
</script>
<template>
<input @input="handleInput" />
</template>
```
Here, declaring `input` is correct because you want to intercept and transform the native event before passing it to the parent.
## Debugging Tips
If your click handlers aren't firing:
1. Check if the event is declared in `emits`
2. If declared, ensure you're calling `emit('click')` somewhere
3. If you want native behavior, remove from `emits` declaration
4. Use Vue DevTools to see which events are being emitted
```vue
<script setup>
const emit = defineEmits(['click'])
function handleClick(event) {
console.log('Native click received, now emitting component event')
emit('click', event)
}
</script>
<template>
<div @click="handleClick">Click me</div>
</template>
```
## Reference
- [Vue.js Component Events](https://vuejs.org/guide/components/events.html)
- [Vue.js Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html)
@@ -0,0 +1,141 @@
---
title: Never Use .passive and .prevent Together
impact: HIGH
impactDescription: Conflicting modifiers cause .prevent to be ignored and trigger browser warnings
type: gotcha
tags: [vue3, events, modifiers, scroll, touch, performance]
---
# Never Use .passive and .prevent Together
**Impact: HIGH** - The `.passive` modifier tells the browser you will NOT call `preventDefault()`, while `.prevent` does exactly that. Using them together causes `.prevent` to be ignored and triggers browser console warnings. This is a logical contradiction that leads to broken event handling.
## Task Checklist
- [ ] Never combine `.passive` and `.prevent` on the same event
- [ ] Use `.passive` for scroll/touch events where you want better performance
- [ ] Use `.prevent` when you need to stop the default browser action
- [ ] If you need conditional prevention, handle it in JavaScript without `.passive`
**Incorrect:**
```html
<!-- WRONG: Conflicting modifiers -->
<template>
<div @scroll.passive.prevent="handleScroll">
<!-- .prevent will be IGNORED -->
<!-- Browser shows warning -->
</div>
</template>
```
```html
<!-- WRONG: On touch events -->
<template>
<div @touchstart.passive.prevent="handleTouch">
<!-- Cannot prevent default - passive already promised not to -->
</div>
</template>
```
```html
<!-- WRONG: On wheel events -->
<template>
<div @wheel.passive.prevent="handleWheel">
<!-- Broken: will scroll anyway despite .prevent -->
</div>
</template>
```
**Correct:**
```html
<!-- CORRECT: Use .passive for performance (no prevention needed) -->
<template>
<div @scroll.passive="handleScroll">
<!-- Good for scroll tracking without blocking -->
</div>
</template>
```
```html
<!-- CORRECT: Use .prevent when you need to prevent default -->
<template>
<form @submit.prevent="handleSubmit">
<!-- Correctly prevents form submission -->
</form>
</template>
```
```html
<!-- CORRECT: For touch events where you need to prevent -->
<template>
<div @touchmove="handleTouchMove">
<!-- Handle prevention conditionally in JS -->
</div>
</template>
<script setup>
function handleTouchMove(event) {
if (shouldPreventScroll.value) {
event.preventDefault()
}
// ... handle touch
}
</script>
```
## Understanding .passive
```javascript
// .passive tells the browser:
// "I promise I won't call preventDefault()"
// This allows the browser to:
// 1. Start scrolling immediately without waiting for JS
// 2. Improve scroll performance, especially on mobile
// 3. Reduce jank and stuttering
// Equivalent to:
element.addEventListener('scroll', handler, { passive: true })
```
## When to Use .passive
```html
<!-- Good use cases for .passive -->
<!-- Scroll tracking analytics -->
<div @scroll.passive="trackScrollPosition">
<!-- Touch gesture detection (no prevention needed) -->
<div @touchmove.passive="detectGesture">
<!-- Wheel event monitoring -->
<div @wheel.passive="monitorWheel">
```
## When to Use .prevent (Without .passive)
```html
<!-- Good use cases for .prevent -->
<!-- Form submission -->
<form @submit.prevent="handleSubmit">
<!-- Link clicks with custom navigation -->
<a @click.prevent="navigate">
<!-- Preventing context menu -->
<div @contextmenu.prevent="showCustomMenu">
```
## Browser Warning
When you combine `.passive` and `.prevent`, the browser console shows:
```
[Intervention] Unable to preventDefault inside passive event listener
due to target being treated as passive.
```
## Reference
- [Vue.js Event Handling - Event Modifiers](https://vuejs.org/guide/essentials/event-handling.html#event-modifiers)
- [MDN - Improving scroll performance with passive listeners](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#improving_scrolling_performance_with_passive_listeners)
@@ -0,0 +1,136 @@
---
title: Never Use v-if and v-for on the Same Element
impact: HIGH
impactDescription: Causes confusing precedence issues and Vue 2 to 3 migration bugs
type: capability
tags: [vue3, v-if, v-for, conditional-rendering, list-rendering, eslint]
---
# Never Use v-if and v-for on the Same Element
**Impact: HIGH** - Using `v-if` and `v-for` on the same element creates ambiguous precedence that differs between Vue 2 and Vue 3. In Vue 2, `v-for` had higher precedence; in Vue 3, `v-if` has higher precedence. This breaking change causes subtle bugs during migration and makes code intent unclear.
The ESLint rule `vue/no-use-v-if-with-v-for` enforces this best practice.
## Task Checklist
- [ ] Never place v-if and v-for on the same element
- [ ] For filtering list items: use a computed property that filters the array
- [ ] For hiding entire list: wrap with `<template v-if>` around the v-for
- [ ] Enable eslint-plugin-vue rule `vue/no-use-v-if-with-v-for`
**Incorrect:**
```html
<!-- WRONG: v-if and v-for on same element - ambiguous precedence -->
<template>
<!-- Intent: show only active users -->
<li v-for="user in users" v-if="user.isActive" :key="user.id">
{{ user.name }}
</li>
</template>
```
```html
<!-- WRONG: Hiding entire list conditionally -->
<template>
<li v-for="user in users" v-if="shouldShowList" :key="user.id">
{{ user.name }}
</li>
</template>
```
```html
<!-- WRONG: Vue 3 precedence issue -->
<template>
<!-- In Vue 3, v-if runs FIRST, so 'user' is undefined! -->
<li v-for="user in users" v-if="user.isActive" :key="user.id">
{{ user.name }}
</li>
<!-- Error: Cannot read property 'isActive' of undefined -->
</template>
```
**Correct:**
```html
<!-- CORRECT: Filter with computed property -->
<template>
<li v-for="user in activeUsers" :key="user.id">
{{ user.name }}
</li>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps(['users'])
const activeUsers = computed(() =>
props.users.filter(user => user.isActive)
)
</script>
```
```html
<!-- CORRECT: Wrap with <template v-if> for conditional list -->
<template>
<template v-if="shouldShowList">
<li v-for="user in users" :key="user.id">
{{ user.name }}
</li>
</template>
</template>
```
```html
<!-- CORRECT: v-if inside the loop (per-item condition) -->
<template>
<ul>
<template v-for="user in users" :key="user.id">
<li v-if="user.isActive">
{{ user.name }}
</li>
</template>
</ul>
</template>
```
## Vue 2 vs Vue 3 Precedence Change
```javascript
// Vue 2: v-for evaluated first
// <li v-for="user in users" v-if="user.isActive">
// Equivalent to: users.forEach(user => { if (user.isActive) render(user) })
// Vue 3: v-if evaluated first
// <li v-for="user in users" v-if="user.isActive">
// Equivalent to: if (user.isActive) users.forEach(user => render(user))
// Problem: 'user' doesn't exist yet when v-if runs!
```
## Why Computed Properties Are Better
```javascript
// Benefits of filtering via computed:
// 1. Clear separation of concerns (logic vs template)
// 2. Cached - only recalculates when dependencies change
// 3. Reusable - can be used elsewhere in component
// 4. Testable - can unit test the filtering logic
// 5. No ambiguity about intent
const activeUsers = computed(() =>
users.value.filter(u => u.isActive)
)
// Can add more complex filtering
const filteredUsers = computed(() =>
users.value
.filter(u => u.isActive)
.filter(u => u.role === selectedRole.value)
.sort((a, b) => a.name.localeCompare(b.name))
)
```
## Reference
- [Vue.js Style Guide - Avoid v-if with v-for](https://vuejs.org/style-guide/rules-essential.html#avoid-v-if-with-v-for)
- [Vue 3 Migration Guide - v-if vs v-for Precedence](https://v3-migration.vuejs.org/breaking-changes/v-if-v-for)
- [ESLint Plugin Vue - no-use-v-if-with-v-for](https://eslint.vuejs.org/rules/no-use-v-if-with-v-for)
@@ -0,0 +1,157 @@
---
title: Return Stable Object References from Computed Properties
impact: MEDIUM
impactDescription: Computed properties returning new objects trigger effects even when values haven't meaningfully changed
type: efficiency
tags: [vue3, computed, performance, reactivity, vue3.4]
---
# Return Stable Object References from Computed Properties
**Impact: MEDIUM** - In Vue 3.4+, computed properties only trigger effects when their value changes. However, if a computed returns a new object each time, Vue cannot detect that the values inside are the same. This causes unnecessary effect re-runs.
For primitive values, Vue 3.4+ handles this automatically. For objects, manually compare and return the previous value when nothing meaningful has changed.
## Task Checklist
- [ ] For computed properties returning primitives, Vue 3.4+ handles stability automatically
- [ ] For computed properties returning objects, compare with previous value and return old reference if unchanged
- [ ] Always perform the full computation before comparing (to track dependencies correctly)
- [ ] Consider if you really need to return an object, or if primitives would suffice
**Incorrect:**
```vue
<script setup>
import { ref, computed, watchEffect } from 'vue'
const count = ref(0)
// BAD: Returns new object every time, always triggers effects
const stats = computed(() => {
return {
isEven: count.value % 2 === 0,
doubleValue: count.value * 2
}
})
watchEffect(() => {
console.log('Stats changed:', stats.value)
// Logs on EVERY count change, even when isEven hasn't changed
// count: 0 -> 2 -> 4: isEven is always true, but effect runs each time
})
</script>
```
**Correct:**
```vue
<script setup>
import { ref, computed, watchEffect } from 'vue'
const count = ref(0)
// GOOD (Vue 3.4+): Primitive computed - automatic stability
const isEven = computed(() => count.value % 2 === 0)
watchEffect(() => {
console.log('isEven:', isEven.value)
// Only logs when isEven actually changes (0, 2, 4 won't re-trigger)
})
// GOOD (Vue 3.4+): Manual comparison for object returns
const stats = computed((oldValue) => {
// Step 1: Always compute the new value first (to track dependencies)
const newValue = {
isEven: count.value % 2 === 0,
category: count.value < 10 ? 'small' : 'large'
}
// Step 2: Compare with previous value
if (oldValue &&
oldValue.isEven === newValue.isEven &&
oldValue.category === newValue.category) {
return oldValue // Return old reference - no effect triggers
}
return newValue
})
watchEffect(() => {
console.log('Stats changed:', stats.value)
// Now only logs when isEven or category actually changes
})
</script>
```
## Primitive vs Object Computed Behavior (Vue 3.4+)
```javascript
import { ref, computed, watchEffect } from 'vue'
const count = ref(0)
// PRIMITIVE: Vue automatically detects value hasn't changed
const isEven = computed(() => count.value % 2 === 0)
watchEffect(() => console.log(isEven.value)) // true
count.value = 2 // isEven still true - NO log
count.value = 4 // isEven still true - NO log
count.value = 3 // isEven now false - logs: false
// OBJECT: New reference every time (without manual comparison)
const obj = computed(() => ({ isEven: count.value % 2 === 0 }))
watchEffect(() => console.log(obj.value)) // { isEven: true }
count.value = 2 // Logs again! New object reference
count.value = 4 // Logs again! New object reference
```
## Advanced: Deep Object Comparison
```javascript
import { ref, computed } from 'vue'
import { isEqual } from 'lodash-es' // For deep comparison
const filters = ref({ category: 'all', sortBy: 'date', page: 1 })
// For complex objects, use deep comparison
const activeFilters = computed((oldValue) => {
const newValue = {
...filters.value,
hasFilters: filters.value.category !== 'all' || filters.value.sortBy !== 'date'
}
// Deep compare for complex objects
if (oldValue && isEqual(oldValue, newValue)) {
return oldValue
}
return newValue
})
```
## Important: Always Compute Before Comparing
```javascript
// BAD: Early return prevents dependency tracking
const optimized = computed((oldValue) => {
if (oldValue && someCondition) {
return oldValue // Dependencies not tracked!
}
return computeExpensiveValue()
})
// GOOD: Compute first, then compare
const optimized = computed((oldValue) => {
const newValue = computeExpensiveValue() // Always track dependencies
if (oldValue && newValue === oldValue) {
return oldValue
}
return newValue
})
```
## Reference
- [Vue.js Performance - Computed Stability](https://vuejs.org/guide/best-practices/performance.html#computed-stability)
- [Vue.js Computed Properties](https://vuejs.org/guide/essentials/computed.html)
@@ -0,0 +1,140 @@
---
title: Keep Props Stable to Minimize Child Re-renders
impact: HIGH
impactDescription: Passing changing props to list items causes ALL children to re-render unnecessarily
type: efficiency
tags: [vue3, performance, props, v-for, re-renders, optimization]
---
# Keep Props Stable to Minimize Child Re-renders
**Impact: HIGH** - When props passed to child components change, Vue must re-render those components. Passing derived values like `activeId` to every list item causes all items to re-render when activeId changes, even if only one item's active state actually changed.
Move comparison logic to the parent and pass the boolean result instead. This is one of the most impactful update performance optimizations in Vue.
## Task Checklist
- [ ] Avoid passing parent-level state that all children compare against (like `activeId`)
- [ ] Pre-compute derived boolean props in the parent (like `:active="item.id === activeId"`)
- [ ] Profile re-renders using Vue DevTools to identify prop stability issues
- [ ] Consider this pattern especially critical for large lists
**Incorrect:**
```vue
<template>
<!-- BAD: activeId changes -> ALL 100 ListItems re-render -->
<ListItem
v-for="item in list"
:key="item.id"
:id="item.id"
:active-id="activeId"
/>
</template>
<script setup>
import { ref } from 'vue'
const list = ref([/* 100 items */])
const activeId = ref(null)
// When activeId changes from 1 to 2:
// - ListItem 1 needs to re-render (was active, now not)
// - ListItem 2 needs to re-render (was not active, now active)
// - All other 98 ListItems ALSO re-render because activeId prop changed!
</script>
```
```vue
<!-- ListItem.vue - receives activeId and compares internally -->
<template>
<div :class="{ active: id === activeId }">
{{ id }}
</div>
</template>
<script setup>
defineProps({
id: Number,
activeId: Number // This prop changes for ALL items
})
</script>
```
**Correct:**
```vue
<template>
<!-- GOOD: Only items whose :active actually changed will re-render -->
<ListItem
v-for="item in list"
:key="item.id"
:id="item.id"
:active="item.id === activeId"
/>
</template>
<script setup>
import { ref } from 'vue'
const list = ref([/* 100 items */])
const activeId = ref(null)
// When activeId changes from 1 to 2:
// - ListItem 1: :active changed from true to false -> re-renders
// - ListItem 2: :active changed from false to true -> re-renders
// - All other 98 ListItems: :active is still false -> NO re-render!
</script>
```
```vue
<!-- ListItem.vue - receives pre-computed boolean -->
<template>
<div :class="{ active }">
{{ id }}
</div>
</template>
<script setup>
defineProps({
id: Number,
active: Boolean // This only changes for items that truly changed
})
</script>
```
## Common Patterns That Cause Prop Instability
```vue
<!-- BAD: Passing index that could shift -->
<Item
v-for="(item, index) in items"
:key="item.id"
:index="index"
:total="items.length" <!-- Changes when list changes -->
/>
<!-- BAD: Passing entire selection set -->
<Item
v-for="item in items"
:key="item.id"
:selected-ids="selectedIds" <!-- All items re-render on any selection -->
/>
<!-- GOOD: Pre-compute the boolean -->
<Item
v-for="item in items"
:key="item.id"
:selected="selectedIds.includes(item.id)"
/>
```
## Performance Impact Example
| Scenario | Props Changed | Components Re-rendered |
|----------|---------------|------------------------|
| 100 items, pass `activeId` | 100 | 100 (all) |
| 100 items, pass `:active` boolean | 2 | 2 (only changed) |
| 1000 items, pass `activeId` | 1000 | 1000 (all) |
| 1000 items, pass `:active` boolean | 2 | 2 (only changed) |
## Reference
- [Vue.js Performance - Props Stability](https://vuejs.org/guide/best-practices/performance.html#props-stability)
@@ -0,0 +1,109 @@
# Use Global Properties Sparingly in Plugins
## Rule
When using `app.config.globalProperties` in Vue plugins, use them sparingly and with clear naming conventions. Excessive global properties lead to confusion, naming conflicts, and debugging difficulties.
## Why This Matters
1. **Implicit dependencies**: Global properties make component dependencies invisible, making code harder to understand and maintain.
2. **Naming collisions**: Multiple plugins may try to use the same property name (e.g., `$http`, `$api`), causing silent overwrites.
3. **Debugging difficulty**: When issues arise, tracing back to which plugin provides a global property is challenging.
4. **IDE limitations**: Global properties may not have proper autocomplete or type checking without careful configuration.
5. **Testing complexity**: Global state is harder to mock and isolate in unit tests.
## Bad Practice
```typescript
// Too many global properties from various plugins
app.config.globalProperties.$http = axios
app.config.globalProperties.$api = apiClient
app.config.globalProperties.$auth = authService
app.config.globalProperties.$translate = i18n.translate
app.config.globalProperties.$format = formatters
app.config.globalProperties.$utils = utilities
app.config.globalProperties.$config = appConfig
app.config.globalProperties.$logger = logger
// In component - where did all these come from?
export default {
mounted() {
this.$logger.info('Mounted')
const data = await this.$http.get(this.$config.apiUrl)
this.$api.process(this.$utils.transform(data))
}
}
```
## Good Practice
```typescript
// Use provide/inject for most functionality
export default {
install(app, options) {
// Provide services via injection
app.provide('api', apiClient)
app.provide('auth', authService)
app.provide('i18n', i18n)
// Reserve globalProperties for truly global template helpers
// that are used extensively in templates across the app
app.config.globalProperties.$t = i18n.translate // Common convention
}
}
// In component - explicit dependencies
<script setup>
import { inject } from 'vue'
const api = inject('api')
const auth = inject('auth')
</script>
<template>
<!-- $t is acceptable for common template-only usage -->
<h1>{{ $t('welcome') }}</h1>
</template>
```
## Naming Conventions
If you do use globalProperties:
1. **Use `$` prefix**: This is the Vue convention and avoids conflicts with component data/methods
2. **Use unique prefixes for your library**: e.g., `$myLib_translate` for third-party plugins
3. **Document all global properties**: Keep a central registry of what each plugin provides
```typescript
// Good: namespaced to avoid conflicts
app.config.globalProperties.$myPlugin = {
translate: (key) => /* ... */,
format: (value) => /* ... */
}
// Usage
{{ $myPlugin.translate('key') }}
```
## Auditing Global Properties
You can inspect all global properties for debugging:
```typescript
console.log(app.config.globalProperties)
```
## When Global Properties Are Acceptable
1. **Template-only utilities** used very frequently (like `$t` for translations)
2. **Legacy migration** when transitioning from Vue 2
3. **Libraries that need Options API compatibility** (but prefer also providing inject)
## References
- [Vue.js Plugins Documentation](https://vuejs.org/guide/reusability/plugins.html)
- [Vue.js Global Properties](https://vuejs.org/api/application.html#app-config-globalproperties)
@@ -0,0 +1,124 @@
# Install Plugins Before Mounting the App
## Rule
All plugins must be installed using `app.use()` BEFORE calling `app.mount()`. Installing plugins after the app is mounted can lead to reactivity issues, missing dependencies, and unexpected behavior.
## Why This Matters
1. **Hidden dependencies**: Components may render before plugins they depend on are available, causing runtime errors.
2. **Reactivity issues**: Late plugin installation can cause subtle reactivity problems where provided values aren't properly reactive.
3. **Initialization order**: Many plugins (like vue-router, pinia) need to set up state before any component renders.
4. **Ecosystem complexity**: Adding plugins after mount can cause issues with Vue's internal ecosystem and hydration in SSR scenarios.
## Bad Practice
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import i18nPlugin from './plugins/i18n'
const app = createApp(App)
// Mounting first - plugins not yet available!
app.mount('#app')
// Installing after mount - TOO LATE!
app.use(router)
app.use(i18nPlugin, { locale: 'en' })
```
## Good Practice
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
import i18nPlugin from './plugins/i18n'
const app = createApp(App)
// Install all plugins BEFORE mounting
app.use(createPinia())
app.use(router)
app.use(i18nPlugin, { locale: 'en' })
// Mount LAST
app.mount('#app')
```
## Plugin Installation Order
The order of `app.use()` calls can matter when plugins depend on each other:
```typescript
const app = createApp(App)
// 1. State management first (other plugins might need it)
app.use(createPinia())
// 2. Router (may depend on state)
app.use(router)
// 3. Other plugins (may depend on router or state)
app.use(authPlugin)
app.use(i18nPlugin, { locale: 'en' })
// 4. Mount last
app.mount('#app')
```
## Async Plugin Installation
If you need to perform async operations before mounting:
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import { loadPlugins } from './plugins'
async function bootstrap() {
const app = createApp(App)
// Await async plugin setup
const i18nPlugin = await loadI18nMessages()
// Install all plugins
app.use(i18nPlugin)
// Mount after everything is ready
app.mount('#app')
}
bootstrap()
```
## Duplicate Installation Protection
Vue's `app.use()` automatically prevents duplicate plugin installation:
```typescript
app.use(myPlugin)
app.use(myPlugin) // This second call is ignored - no double installation
// This is handled internally by Vue, providing a safety net
```
## Common Symptoms of Late Plugin Installation
- `inject()` returns `undefined` unexpectedly
- Router navigation guards not firing
- Store state not reactive
- Template errors about undefined global properties
- Hydration mismatches in SSR
## References
- [Vue.js Plugins Documentation](https://vuejs.org/guide/reusability/plugins.html)
- [Vue.js Application API](https://vuejs.org/api/application.html)
- [Vue 3 Migration Guide - Global API](https://v3-migration.vuejs.org/breaking-changes/global-api.html)
@@ -0,0 +1,120 @@
# Prefer provide/inject Over Global Properties in Plugins
## Rule
When creating Vue plugins, prefer using `app.provide()` to make plugin functionality available to components instead of attaching properties to `app.config.globalProperties`.
## Why This Matters
1. **globalProperties don't work in setup()**: Properties attached to `globalProperties` are only accessible via `this` in Options API. They are NOT available in the Composition API's `setup()` function.
2. **Type safety**: `provide/inject` integrates better with TypeScript and requires less type augmentation boilerplate.
3. **Testability**: Injected dependencies are easier to mock in tests compared to global properties.
4. **Code clarity**: Explicit `inject()` calls make dependencies visible, while global properties can appear "magic".
5. **Scoping**: `provide/inject` follows Vue's component hierarchy, making it easier to provide different values to different parts of your app.
## Bad Practice
```typescript
// plugins/i18n.ts
export default {
install(app, options) {
// Attaching to globalProperties - only works with Options API
app.config.globalProperties.$translate = (key: string) => {
return key.split('.').reduce((o, i) => o?.[i], options)
}
}
}
// In component - requires type augmentation for TypeScript
// Also DOES NOT work in <script setup>
export default {
mounted() {
console.log(this.$translate('greeting.hello'))
}
}
```
## Good Practice
```typescript
// plugins/i18n.ts
import type { InjectionKey, App } from 'vue'
export interface I18nOptions {
[key: string]: string | I18nOptions
}
export interface I18n {
translate: (key: string) => string
options: I18nOptions
}
export const i18nKey: InjectionKey<I18n> = Symbol('i18n')
export default {
install(app: App, options: I18nOptions) {
const translate = (key: string): string => {
return key.split('.').reduce((o, i) => o?.[i], options) as string ?? key
}
// Use provide for Composition API compatibility
app.provide(i18nKey, { translate, options })
}
}
// In component - works in setup() and has full type safety
<script setup lang="ts">
import { inject } from 'vue'
import { i18nKey } from '@/plugins/i18n'
const i18n = inject(i18nKey)
console.log(i18n?.translate('greeting.hello'))
</script>
```
## Hybrid Approach
If you must support both APIs (e.g., for backwards compatibility), provide both:
```typescript
export default {
install(app: App, options: I18nOptions) {
const i18n = {
translate: (key: string) => /* ... */
}
// For Composition API
app.provide(i18nKey, i18n)
// For Options API (use sparingly)
app.config.globalProperties.$i18n = i18n
}
}
```
## TypeScript Type Augmentation (if using globalProperties)
If you must use globalProperties, you need proper type augmentation:
```typescript
// types/vue.d.ts
export {}
declare module 'vue' {
interface ComponentCustomProperties {
$translate: (key: string) => string
}
}
```
**Important**: The file MUST contain `export {}` or another top-level export/import. Without it, the augmentation will OVERWRITE types instead of augmenting them.
## References
- [Vue.js Plugins Documentation](https://vuejs.org/guide/reusability/plugins.html)
- [Vue.js Provide/Inject](https://vuejs.org/guide/components/provide-inject.html)
- [TypeScript with Options API](https://vuejs.org/guide/typescript/options-api.html)
@@ -0,0 +1,157 @@
# Proper TypeScript Type Augmentation for Plugins
## Rule
When creating Vue plugins that add global properties, you MUST properly augment TypeScript types. The augmentation file MUST contain at least one top-level `import` or `export` statement to be treated as a module.
## Why This Matters
1. **Without module syntax, types are overwritten**: If your augmentation file isn't a module, it will OVERWRITE Vue's types instead of augmenting them, breaking type checking for the entire application.
2. **Type safety**: Proper augmentation enables autocomplete and type checking for plugin-provided properties.
3. **IDE support**: Developers get proper IntelliSense for global properties like `this.$translate`.
4. **Error prevention**: Catch typos and incorrect usage at compile time rather than runtime.
## Critical Rule: Module Syntax Required
```typescript
// BAD - This OVERWRITES Vue types instead of augmenting!
// types/vue.d.ts
declare module 'vue' {
interface ComponentCustomProperties {
$translate: (key: string) => string
}
}
// GOOD - The export {} makes this a module, so it AUGMENTS types
// types/vue.d.ts
export {} // This line is CRITICAL!
declare module 'vue' {
interface ComponentCustomProperties {
$translate: (key: string) => string
}
}
```
## Complete Plugin Type Augmentation Example
```typescript
// plugins/i18n.ts
import type { App, InjectionKey } from 'vue'
export interface I18nOptions {
locale: string
messages: Record<string, Record<string, string>>
}
export interface I18nInstance {
translate: (key: string) => string
locale: string
}
export const i18nInjectionKey: InjectionKey<I18nInstance> = Symbol('i18n')
export function createI18n(options: I18nOptions) {
const i18n: I18nInstance = {
translate(key: string) {
return options.messages[options.locale]?.[key] ?? key
},
locale: options.locale
}
return {
install(app: App) {
// For Composition API
app.provide(i18nInjectionKey, i18n)
// For Options API / templates
app.config.globalProperties.$t = i18n.translate
app.config.globalProperties.$i18n = i18n
}
}
}
// types/i18n.d.ts (or in the same file after export)
export {}
declare module 'vue' {
interface ComponentCustomProperties {
$t: (key: string) => string
$i18n: I18nInstance
}
}
```
## Alternative: Augment @vue/runtime-core
Some plugins augment `@vue/runtime-core` instead of `vue`:
```typescript
// types/global.d.ts
export {}
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$myPlugin: MyPluginInstance
}
}
```
Both approaches work, but `'vue'` is more common in application code.
## Ensure tsconfig.json Includes the Declaration File
```json
{
"compilerOptions": {
// ...
},
"include": [
"src/**/*.ts",
"src/**/*.vue",
"types/**/*.d.ts" // Include your declaration files
]
}
```
## For Library Authors: package.json Types Field
If publishing a plugin as a package:
```json
{
"name": "my-vue-plugin",
"types": "./dist/types/index.d.ts",
"exports": {
".": {
"types": "./dist/types/index.d.ts",
"import": "./dist/index.mjs"
}
}
}
```
## Common Errors and Solutions
### Error: Property '$xyz' does not exist on type
1. Check that your `.d.ts` file has `export {}` or an import statement
2. Verify the file is included in `tsconfig.json`
3. Restart your TypeScript language server (VS Code: Cmd+Shift+P > "Restart TS Server")
### Error: Types work in some components but not others
This often happens when using Vetur instead of Volar. If you're on Vue 3, switch to Volar (Vue - Official extension).
### Error in Options API but not Composition API
Global properties on `this` require proper augmentation of `ComponentCustomProperties`. The Composition API uses `inject()` which is typed separately.
## References
- [Vue.js TypeScript with Options API](https://vuejs.org/guide/typescript/options-api.html)
- [TypeScript Module Augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)
- [Vue.js Plugins Documentation](https://vuejs.org/guide/reusability/plugins.html)
@@ -0,0 +1,161 @@
---
title: defineProps Cannot Access Variables from script setup
impact: MEDIUM
impactDescription: Variables declared in script setup are not accessible inside defineProps arguments
type: gotcha
tags: [vue3, props, script-setup, defineProps, compiler]
---
# defineProps Cannot Access Variables from script setup
**Impact: MEDIUM** - Code inside the `defineProps()` argument cannot access other variables declared in `<script setup>`. The entire expression is moved to an outer function scope when compiled, making local variables inaccessible.
This commonly surprises developers trying to use imported constants or computed validation logic.
## Task Checklist
- [ ] Define validation constants outside `<script setup>` or in a separate file
- [ ] Import constants before using them in defineProps
- [ ] Use external type definitions for TypeScript props
- [ ] For dynamic validation, use watchers instead of prop validators
**Incorrect:**
```vue
<script setup>
import { ref } from 'vue'
// These are in <script setup> scope
const VALID_SIZES = ['sm', 'md', 'lg']
const maxLength = ref(100)
defineProps({
size: {
type: String,
// WRONG: VALID_SIZES is not accessible here
validator: (v) => VALID_SIZES.includes(v) // ReferenceError!
},
name: {
type: String,
// WRONG: Cannot access refs
validator: (v) => v.length <= maxLength.value // ReferenceError!
}
})
</script>
```
**Correct:**
```vue
<script>
// Define constants in regular <script> block (module scope)
export const VALID_SIZES = ['sm', 'md', 'lg']
export const MAX_LENGTH = 100
</script>
<script setup>
// Now accessible in defineProps
defineProps({
size: {
type: String,
validator: (v) => VALID_SIZES.includes(v) // Works!
},
name: {
type: String,
validator: (v) => v.length <= MAX_LENGTH // Works!
}
})
</script>
```
## Pattern: Import from External File
```javascript
// validation.js
export const VALID_SIZES = ['sm', 'md', 'lg']
export const VALID_COLORS = ['red', 'blue', 'green']
export const sizeValidator = (v) => VALID_SIZES.includes(v)
```
```vue
<script setup>
import { VALID_SIZES, VALID_COLORS, sizeValidator } from './validation'
// Imported values ARE accessible
defineProps({
size: {
type: String,
validator: sizeValidator
},
color: {
type: String,
validator: (v) => VALID_COLORS.includes(v)
}
})
</script>
```
## Pattern: Dual Script Blocks
```vue
<script>
// Regular script for module-level declarations
const options = {
themes: ['light', 'dark', 'system'],
defaults: {
theme: 'light',
size: 'md'
}
}
</script>
<script setup>
// options is accessible here
const props = defineProps({
theme: {
type: String,
default: options.defaults.theme,
validator: (v) => options.themes.includes(v)
}
})
</script>
```
## TypeScript: External Type Definitions
```typescript
// types.ts
export interface UserProps {
name: string
email: string
age?: number
}
```
```vue
<script setup lang="ts">
import type { UserProps } from './types'
// Type imports work fine
const props = defineProps<UserProps>()
</script>
```
## Why This Happens
Vue's compiler transforms `<script setup>` code. The `defineProps()` call is extracted and moved to component options at compile time, before the setup function runs:
```javascript
// Your code:
const MY_CONST = 'value'
defineProps({ prop: { default: MY_CONST } })
// Compiled (simplified):
export default {
props: { prop: { default: MY_CONST } }, // MY_CONST doesn't exist here!
setup() {
const MY_CONST = 'value' // Defined too late
}
}
```
## Reference
- [Vue.js Script Setup - defineProps](https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits)
@@ -0,0 +1,203 @@
---
title: Provide/Inject Has Limited DevTools Support - Plan for Debugging
impact: LOW
impactDescription: Unlike props and state, provided values are harder to trace in Vue DevTools, making debugging more challenging
type: gotcha
tags: [vue3, provide-inject, debugging, devtools, architecture]
---
# Provide/Inject Has Limited DevTools Support - Plan for Debugging
**Impact: LOW** - While provide/inject is powerful for avoiding prop drilling, it creates less visible data flow than props. Provided values are not as easily inspectable in Vue DevTools, and tracing where a value comes from requires navigating the component tree manually.
## Task Checklist
- [ ] Document provided values at the provider component level
- [ ] Use descriptive Symbol descriptions for easier identification
- [ ] Consider adding development-only logging for provided state changes
- [ ] Keep provide/inject chains shallow when possible
- [ ] Prefer Pinia for complex state that needs DevTools integration
## The Challenge
Unlike props which are clearly visible in Vue DevTools for each component, provided values:
1. Don't show which ancestor provided them
2. Require manual navigation to find the provider
3. Don't show in the standard props/data panels
4. Can be shadowed by closer ancestors using the same key
## Strategies for Better Debugging
### 1. Use Descriptive Symbol Names
```js
// injection-keys.js
// BETTER: Descriptive names appear in errors and debugging
export const UserAuthKey = Symbol('UserAuthenticationState')
export const ThemeConfigKey = Symbol('ThemeConfiguration')
export const FormContextKey = Symbol('FormValidationContext')
// WORSE: Generic names are harder to trace
export const UserKey = Symbol()
export const ThemeKey = Symbol('theme')
```
### 2. Document Providers Clearly
```vue
<!-- AuthProvider.vue -->
<script setup>
/**
* Authentication Provider
*
* Provides:
* - UserAuthKey: Current user state (Ref<User | null>)
* - AuthActionsKey: { login, logout, refresh }
*
* Must wrap any component that needs authentication state.
*/
import { provide, ref, readonly } from 'vue'
import { UserAuthKey, AuthActionsKey } from '@/injection-keys'
const user = ref(null)
// ... implementation
provide(UserAuthKey, readonly(user))
provide(AuthActionsKey, { login, logout, refresh })
</script>
```
### 3. Development-Only Logging
```js
// composables/useProvideWithLogging.js
import { provide, watch, getCurrentInstance } from 'vue'
export function useProvideWithLogging(key, value, name) {
provide(key, value)
if (import.meta.env.DEV) {
const instance = getCurrentInstance()
const componentName = instance?.type?.name || 'Unknown'
console.log(`[Provide] ${name} provided by <${componentName}>`)
// Log reactive changes
if (value && typeof value === 'object' && 'value' in value) {
watch(value, (newVal) => {
console.log(`[Provide] ${name} changed:`, newVal)
}, { deep: true })
}
}
}
```
```vue
<script setup>
import { ref } from 'vue'
import { useProvideWithLogging } from '@/composables/useProvideWithLogging'
import { ThemeKey } from '@/injection-keys'
const theme = ref('dark')
// In development, logs when provided and when changed
useProvideWithLogging(ThemeKey, theme, 'Theme')
</script>
```
### 4. Inject with Missing Provider Warnings
```js
// composables/useSafeInject.js
import { inject, getCurrentInstance } from 'vue'
export function useSafeInject(key, fallback, keyName) {
const value = inject(key, undefined)
if (value === undefined) {
const instance = getCurrentInstance()
const componentName = instance?.type?.name || 'Unknown'
if (import.meta.env.DEV) {
console.warn(
`[Inject] ${keyName || String(key)} not provided. ` +
`Component <${componentName}> is using fallback value. ` +
`Ensure a provider exists in the ancestor chain.`
)
}
return typeof fallback === 'function' ? fallback() : fallback
}
return value
}
```
```vue
<script setup>
import { useSafeInject } from '@/composables/useSafeInject'
import { ThemeKey } from '@/injection-keys'
// Warns in dev if no provider found
const theme = useSafeInject(ThemeKey, () => ({ mode: 'light' }), 'ThemeConfig')
</script>
```
### 5. Create Provider Registry for Complex Apps
```js
// utils/provider-registry.js
const providerRegistry = new Map()
export function registerProvider(key, componentName, value) {
if (import.meta.env.DEV) {
providerRegistry.set(key, {
componentName,
value,
timestamp: Date.now()
})
}
}
export function getProviderInfo(key) {
return providerRegistry.get(key)
}
// For DevTools custom plugin or debugging
export function getAllProviders() {
return Object.fromEntries(providerRegistry)
}
// Expose to window for console debugging
if (import.meta.env.DEV) {
window.__VUE_PROVIDERS__ = {
getAll: getAllProviders,
get: getProviderInfo
}
}
```
## When to Use Pinia Instead
If you find yourself needing extensive debugging for state:
| Use Provide/Inject | Use Pinia |
|-------------------|-----------|
| Component library internals | Application-wide state |
| Theme/locale configuration | User session data |
| Form context | Shopping cart |
| Simple parent-child sharing | Complex state with actions |
| Plugin configuration | State that needs time-travel debugging |
Pinia provides excellent DevTools integration with:
- State inspection
- Time-travel debugging
- Action logging
- Hot module replacement
## Reference
- [Vue DevTools](https://devtools.vuejs.org/)
- [Pinia DevTools](https://pinia.vuejs.org/core-concepts/index.html#devtools)
@@ -0,0 +1,244 @@
---
title: Use Factory Functions for Non-Primitive Inject Default Values
impact: MEDIUM
impactDescription: Using object literals as default values creates shared references across all consuming components
type: gotcha
tags: [vue3, provide-inject, composition-api, memory, shared-state]
---
# Use Factory Functions for Non-Primitive Inject Default Values
**Impact: MEDIUM** - When providing default values for `inject()`, using an object literal creates a single shared reference. All components using that default will share the same object, leading to unexpected state sharing and bugs.
## Task Checklist
- [ ] Always use factory functions for object/array default values in inject
- [ ] Pass `true` as the third argument to enable factory mode in Composition API
- [ ] Use the object syntax with factory function in Options API
- [ ] Only use literal defaults for primitive values (strings, numbers, booleans)
## The Gotcha: Shared Default References
**Wrong - Object literal creates shared reference:**
```vue
<script setup>
import { inject } from 'vue'
// WRONG: All components without a provider share this SAME object
const config = inject('config', { debug: false, apiUrl: '' })
// If one component does this:
config.debug = true
// ALL other components using this default now have debug: true!
</script>
```
**Correct - Factory function creates unique instance:**
```vue
<script setup>
import { inject } from 'vue'
// CORRECT: Each component gets its own object
// Third argument `true` indicates the second arg is a factory function
const config = inject('config', () => ({ debug: false, apiUrl: '' }), true)
</script>
```
## API Explanation
The `inject()` function has multiple signatures:
```ts
// Simple default value (OK for primitives)
inject(key, defaultValue)
// Factory function for non-primitives (REQUIRED for objects/arrays)
inject(key, factoryFunction, true)
```
The third argument `true` tells Vue that the second argument is a factory function, not the default value itself.
## Examples
### Primitive Defaults (No Factory Needed)
```vue
<script setup>
import { inject } from 'vue'
// Primitives are safe without factory
const count = inject('count', 0)
const name = inject('name', 'Guest')
const enabled = inject('enabled', false)
</script>
```
### Object Defaults (Factory Required)
```vue
<script setup>
import { inject } from 'vue'
// Objects MUST use factory
const user = inject('user', () => ({
id: null,
name: 'Anonymous',
preferences: {}
}), true)
const settings = inject('settings', () => ({
theme: 'light',
language: 'en',
notifications: true
}), true)
</script>
```
### Array Defaults (Factory Required)
```vue
<script setup>
import { inject } from 'vue'
// Arrays MUST use factory
const items = inject('items', () => [], true)
const permissions = inject('permissions', () => ['read'], true)
</script>
```
### Class Instance Defaults (Factory Required)
```vue
<script setup>
import { inject } from 'vue'
import { Logger } from '@/utils/logger'
// Class instances MUST use factory
const logger = inject('logger', () => new Logger({ level: 'warn' }), true)
</script>
```
## Options API Syntax
In Options API, use the object syntax with a `default` factory function:
```js
export default {
inject: {
// Primitive - can use literal
theme: {
from: 'theme',
default: 'light'
},
// Object - MUST use factory
config: {
from: 'config',
default: () => ({ debug: false })
},
// Array - MUST use factory
permissions: {
from: 'permissions',
default: () => []
}
}
}
```
## Real-World Example: Form Context
```vue
<!-- FormProvider.vue -->
<script setup>
import { provide, reactive } from 'vue'
const formContext = reactive({
values: {},
errors: {},
touched: {},
isSubmitting: false
})
provide('formContext', formContext)
</script>
<!-- FormField.vue (might be used outside FormProvider) -->
<script setup>
import { inject } from 'vue'
// Safe default that won't be shared
const formContext = inject('formContext', () => ({
values: {},
errors: {},
touched: {},
isSubmitting: false,
// Mark as standalone mode
isStandalone: true
}), true)
// Component works both inside and outside FormProvider
</script>
```
## TypeScript: Typing Factory Defaults
```ts
import { inject } from 'vue'
import type { InjectionKey } from 'vue'
interface Config {
apiUrl: string
debug: boolean
features: string[]
}
const ConfigKey: InjectionKey<Config> = Symbol('config')
// TypeScript understands the factory return type
const config = inject(ConfigKey, () => ({
apiUrl: 'https://api.example.com',
debug: false,
features: []
}), true)
```
## Common Mistake in Testing
This gotcha often appears in tests where components are rendered without providers:
```ts
// test.spec.ts
import { mount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'
// Without provider, all test instances share the wrong default
it('test 1', () => {
const wrapper = mount(MyComponent)
wrapper.vm.config.debug = true // Pollutes other tests!
})
it('test 2', () => {
const wrapper = mount(MyComponent)
// Might fail because debug is still true from test 1
})
```
**Fix: Use factory functions in the component, or provide in tests:**
```ts
it('test with provider', () => {
const wrapper = mount(MyComponent, {
global: {
provide: {
config: { debug: false, apiUrl: '' }
}
}
})
})
```
## Reference
- [Vue.js inject() API Reference](https://vuejs.org/api/composition-api-dependency-injection.html#inject)
- [Vue.js Provide/Inject Guide](https://vuejs.org/guide/components/provide-inject.html)
@@ -0,0 +1,226 @@
---
title: Provide/Inject Values Are Not Reactive by Default
impact: HIGH
impactDescription: Provided primitive values lose reactivity, causing injecting components to not update when the source value changes
type: gotcha
tags: [vue3, provide-inject, reactivity, composition-api, options-api]
---
# Provide/Inject Values Are Not Reactive by Default
**Impact: HIGH** - A common misconception is that provide/inject automatically maintains reactivity. By default, provided primitive values are NOT reactive. If the provided value changes in the provider, injecting components will NOT be updated.
## Task Checklist
- [ ] Always wrap primitive values in `ref()` before providing
- [ ] Use `computed()` in Options API `provide()` for reactive data
- [ ] Never destructure refs when providing - pass the ref directly
- [ ] Understand that provided refs are NOT auto-unwrapped in injectors
## The Gotcha: Primitives Lose Reactivity
**Wrong - Primitive loses reactivity:**
```vue
<!-- Provider.vue -->
<script setup>
import { ref, provide } from 'vue'
const count = ref(0)
// WRONG: Providing the unwrapped value loses reactivity
provide('count', count.value) // Provides 0, not a reactive value
function increment() {
count.value++ // Injector will NOT see this change
}
</script>
```
```vue
<!-- Injector.vue -->
<script setup>
import { inject } from 'vue'
const count = inject('count') // Gets 0, forever static
</script>
<template>
<!-- This will always show 0 -->
<div>Count: {{ count }}</div>
</template>
```
**Correct - Provide the ref itself:**
```vue
<!-- Provider.vue -->
<script setup>
import { ref, provide } from 'vue'
const count = ref(0)
// CORRECT: Provide the ref, not the value
provide('count', count)
function increment() {
count.value++ // Injector WILL see this change
}
</script>
```
```vue
<!-- Injector.vue -->
<script setup>
import { inject } from 'vue'
// The ref is injected as-is, maintaining reactivity
const count = inject('count')
</script>
<template>
<!-- Access .value in script, auto-unwrapped in template -->
<div>Count: {{ count }}</div>
</template>
```
## Options API: Use computed() for Reactivity
In Options API, the `provide` option with plain properties is NOT reactive:
**Wrong - Options API without computed:**
```js
export default {
data() {
return {
message: 'Hello'
}
},
// WRONG: This is NOT reactive
provide() {
return {
message: this.message // Provides 'Hello' as a static string
}
}
}
```
**Correct - Use computed() in Options API:**
```js
import { computed } from 'vue'
export default {
data() {
return {
message: 'Hello'
}
},
provide() {
return {
// CORRECT: Wrap in computed for reactivity
message: computed(() => this.message)
}
}
}
```
## Understanding Ref Behavior in Inject
When you provide a ref, it is injected as-is and NOT auto-unwrapped:
```vue
<!-- Provider.vue -->
<script setup>
import { ref, provide } from 'vue'
const user = ref({ name: 'John' })
provide('user', user)
</script>
```
```vue
<!-- Injector.vue -->
<script setup>
import { inject } from 'vue'
const user = inject('user')
// In script, access with .value
console.log(user.value.name) // 'John'
function updateName(newName) {
user.value.name = newName // Works, but mutations should be in provider
}
</script>
<template>
<!-- In template, auto-unwrapped at top level -->
<div>{{ user.name }}</div>
</template>
```
## Providing Reactive Objects
Reactive objects (created with `reactive()`) maintain reactivity when provided:
```vue
<!-- Provider.vue -->
<script setup>
import { reactive, provide } from 'vue'
const state = reactive({
count: 0,
message: 'Hello'
})
provide('state', state)
</script>
```
```vue
<!-- Injector.vue -->
<script setup>
import { inject } from 'vue'
const state = inject('state')
// state.count and state.message are reactive
</script>
```
## Common Mistake: Destructuring Breaks Reactivity
**Wrong - Destructuring provided reactive state:**
```vue
<script setup>
import { inject } from 'vue'
// WRONG: Destructuring loses reactivity
const { count, message } = inject('state')
// count and message are now static values
</script>
```
**Correct - Keep the reference intact:**
```vue
<script setup>
import { inject, toRefs } from 'vue'
const state = inject('state')
// Use state.count and state.message directly
// Or use toRefs if you need destructured reactive refs
const { count, message } = toRefs(state)
</script>
```
## Debugging Tip
If your injected value isn't updating:
1. Check if you provided `ref.value` instead of `ref`
2. Check if you destructured a reactive object
3. In Options API, ensure you used `computed()`
4. Use Vue DevTools to inspect the provided values
## Reference
- [Vue.js Provide/Inject - Working with Reactivity](https://vuejs.org/guide/components/provide-inject.html#working-with-reactivity)
- [How to make provide/inject reactive - LogRocket Blog](https://blog.logrocket.com/how-to-make-provide-inject-reactive/)
- [GitHub Issue: Inject/Provide is not reactive](https://github.com/vuejs/vue/issues/7017)
@@ -0,0 +1,235 @@
---
title: Provide Must Be Called Synchronously During Setup
impact: HIGH
impactDescription: Calling provide() asynchronously or conditionally may fail silently or cause inconsistent injection behavior
type: gotcha
tags: [vue3, provide-inject, composition-api, async, setup]
---
# Provide Must Be Called Synchronously During Setup
**Impact: HIGH** - The `provide()` function must be called synchronously during the component's `setup()` phase. Calling it asynchronously (inside callbacks, promises, or after await) will fail silently, and descendant components will not receive the provided value.
## Task Checklist
- [ ] Always call `provide()` at the top level of `setup()` or `<script setup>`
- [ ] Never call `provide()` inside async callbacks or after await statements
- [ ] For async data, provide a ref first, then update its value later
- [ ] Use immediate `provide()` with reactive containers for dynamic data
## The Gotcha: Async Provide Fails Silently
**Wrong - Provide after async operation:**
```vue
<script setup>
import { provide } from 'vue'
// WRONG: provide() called after await - will NOT work
onMounted(async () => {
const userData = await fetchUser()
provide('user', userData) // Silent failure!
})
</script>
```
**Wrong - Provide inside callback:**
```vue
<script setup>
import { provide } from 'vue'
// WRONG: provide() inside callback - will NOT work
setTimeout(() => {
provide('config', { theme: 'dark' }) // Silent failure!
}, 0)
</script>
```
**Wrong - Provide after await in setup:**
```vue
<script setup>
import { provide } from 'vue'
const response = await fetch('/api/config')
const config = await response.json()
// WRONG: This is after an await, setup context may be lost
provide('config', config) // May not work reliably
</script>
```
## Solution: Provide Synchronously, Update Async
**Correct - Provide ref immediately, update later:**
```vue
<script setup>
import { provide, ref, onMounted } from 'vue'
// Provide immediately with initial value
const user = ref(null)
const isLoading = ref(true)
const error = ref(null)
provide('userState', {
user,
isLoading,
error
})
// Update the ref values asynchronously
onMounted(async () => {
try {
const userData = await fetchUser()
user.value = userData
} catch (e) {
error.value = e
} finally {
isLoading.value = false
}
})
</script>
```
```vue
<!-- Consumer component -->
<script setup>
import { inject } from 'vue'
const { user, isLoading, error } = inject('userState')
</script>
<template>
<div v-if="isLoading">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<div v-else>Welcome, {{ user?.name }}</div>
</template>
```
## Pattern: Async Data Provider
Create a reusable pattern for async-provided data:
```vue
<!-- AsyncDataProvider.vue -->
<script setup>
import { provide, ref, onMounted, watch } from 'vue'
const props = defineProps({
fetchFn: {
type: Function,
required: true
},
provideKey: {
type: [String, Symbol],
required: true
},
immediate: {
type: Boolean,
default: true
}
})
const data = ref(null)
const isLoading = ref(false)
const error = ref(null)
async function load() {
isLoading.value = true
error.value = null
try {
data.value = await props.fetchFn()
} catch (e) {
error.value = e
} finally {
isLoading.value = false
}
}
// Provide synchronously
provide(props.provideKey, {
data,
isLoading,
error,
reload: load
})
// Fetch asynchronously
if (props.immediate) {
onMounted(load)
}
</script>
<template>
<slot />
</template>
```
Usage:
```vue
<template>
<AsyncDataProvider
:fetch-fn="() => api.getUser(userId)"
provide-key="userData"
>
<UserProfile />
</AsyncDataProvider>
</template>
```
## Why This Happens
Vue's `provide()` relies on the current component instance context, which is only available synchronously during setup. After setup completes:
1. The setup context is cleared
2. `provide()` can't find the current instance
3. The call fails silently (no error thrown)
## Checking for Setup Context
You can verify if setup context is available:
```js
import { getCurrentInstance } from 'vue'
function debugProvide(key, value) {
const instance = getCurrentInstance()
if (!instance) {
console.error(
`provide() called outside setup context. ` +
`Key: ${String(key)}. This will fail silently.`
)
return
}
provide(key, value)
}
```
## App-Level Provide (Exception)
`app.provide()` can be called anytime during app initialization:
```js
// main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// This works - app-level provide
app.provide('appConfig', { version: '1.0.0' })
// Even async is OK at app level before mount
fetchConfig().then(config => {
app.provide('apiConfig', config)
app.mount('#app')
})
```
But once the app is mounted, `app.provide()` should not be called.
## Reference
- [Vue.js Composition API - provide()](https://vuejs.org/api/composition-api-dependency-injection.html#provide)
- [Vue.js Provide/Inject Guide](https://vuejs.org/guide/components/provide-inject.html)
@@ -0,0 +1,89 @@
---
title: Never Destructure reactive() Objects Directly
impact: HIGH
impactDescription: Destructuring reactive objects breaks reactivity - changes won't trigger updates
type: capability
tags: [vue3, reactivity, reactive, composition-api, destructuring]
---
# Never Destructure reactive() Objects Directly
**Impact: HIGH** - Destructuring a `reactive()` object breaks the reactive connection. Updates to destructured variables won't trigger UI updates, leading to stale data display.
Vue's `reactive()` uses JavaScript Proxies to track property access. When you destructure, you extract primitive values from the proxy, losing the reactive connection. This is especially dangerous when destructuring from composables or imported state.
## Task Checklist
- [ ] Never destructure reactive objects directly if you need reactivity
- [ ] Use `toRefs()` to convert reactive object properties to refs before destructuring
- [ ] Consider using `ref()` instead of `reactive()` to avoid this pitfall entirely
- [ ] When importing state from composables, check if it's reactive before destructuring
**Incorrect:**
```javascript
import { reactive } from 'vue'
const state = reactive({
count: 0,
name: 'Vue'
})
// WRONG: Destructuring breaks reactivity
const { count, name } = state
// These updates work on the original state...
state.count++ // state.count is now 1
// ...but the destructured variables are NOT updated
console.log(count) // Still 0! Lost reactivity
```
```javascript
// WRONG: Destructuring from a composable
function useCounter() {
const state = reactive({ count: 0 })
return state
}
const { count } = useCounter() // count is now a non-reactive primitive
```
**Correct:**
```javascript
import { reactive, toRefs } from 'vue'
const state = reactive({
count: 0,
name: 'Vue'
})
// CORRECT: Use toRefs() to maintain reactivity
const { count, name } = toRefs(state)
state.count++
console.log(count.value) // 1 - Reactivity preserved! (note: now needs .value)
```
```javascript
// CORRECT: Return toRefs from composables
function useCounter() {
const state = reactive({ count: 0 })
return toRefs(state) // Now safe to destructure
}
const { count } = useCounter() // count is now a ref, reactivity preserved
```
```javascript
// ALTERNATIVE: Just use ref() to avoid the issue entirely
import { ref } from 'vue'
const count = ref(0)
const name = ref('Vue')
// No destructuring needed, no gotchas
```
## Reference
- [Vue.js Reactivity Fundamentals - reactive()](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#reactive)
- [Vue.js Reactivity API - toRefs()](https://vuejs.org/api/reactivity-utilities.html#torefs)
@@ -0,0 +1,132 @@
---
title: Use Debug Hooks to Trace Reactivity Issues
impact: MEDIUM
impactDescription: Debug hooks help identify which dependencies trigger re-renders and watcher executions
type: efficiency
tags: [vue3, reactivity, debugging, computed, watch, development]
---
# Use Debug Hooks to Trace Reactivity Issues
**Impact: MEDIUM** - Vue provides debug hooks (`onTrack`, `onTrigger`, `renderTracked`, `renderTriggered`) that help identify exactly which reactive dependencies are being tracked and which mutations trigger re-execution. These are invaluable for debugging performance issues and unexpected re-renders.
Debug hooks only work in development mode and are stripped in production builds. Use them to understand why a computed property, watcher, or component is re-executing.
## Task Checklist
- [ ] Use `onTrack` and `onTrigger` options on computed/watch for granular debugging
- [ ] Use `onRenderTracked` and `onRenderTriggered` lifecycle hooks for component render debugging
- [ ] Add `debugger` statements inside hooks to pause execution and inspect state
- [ ] Remove or comment out debug hooks before production (they're no-ops but add clutter)
> **Note:** `onTrack` and `onTrigger` are development-only hooks. They are stripped from production builds and may not fire in test environments (e.g., Vitest, Jest) depending on how Vue is bundled. If you need to verify reactivity behavior in tests, use direct assertions on reactive state changes rather than relying on these debug callbacks.
**Debugging computed properties:**
```javascript
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2, {
onTrack(event) {
// Called when a dependency is tracked
// event.target = the reactive object
// event.key = the property being accessed
debugger
console.log('Tracking:', event)
},
onTrigger(event) {
// Called when a dependency mutation triggers re-computation
debugger
console.log('Triggered by:', event)
}
})
```
**Debugging watchers:**
```javascript
import { ref, watch, watchEffect } from 'vue'
const source = ref(0)
// With watch()
watch(source, (newVal, oldVal) => {
console.log('Changed:', oldVal, '->', newVal)
}, {
onTrack(e) {
debugger // Pause to see what's being tracked
},
onTrigger(e) {
debugger // Pause to see what triggered the watcher
}
})
// With watchEffect()
watchEffect(() => {
console.log('Source is:', source.value)
}, {
onTrack(e) {
console.log('Tracking dependency:', e.key)
},
onTrigger(e) {
console.log('Triggered by:', e.key, 'mutation')
}
})
```
**Debugging component renders:**
```vue
<script setup>
import { onRenderTracked, onRenderTriggered, ref } from 'vue'
const count = ref(0)
// Called for every reactive dependency accessed during render
onRenderTracked((event) => {
console.log('Render tracked:', event.key, 'from', event.target)
debugger // Pause to inspect which dependencies are tracked
})
// Called when a reactive dependency triggers re-render
onRenderTriggered((event) => {
console.log('Render triggered by:', event.key)
console.log('Old value:', event.oldValue)
console.log('New value:', event.newValue)
debugger // Pause to see exactly what caused the re-render
})
</script>
```
**Options API equivalent:**
```javascript
export default {
data() {
return { count: 0 }
},
renderTracked(event) {
console.log('Dependency tracked during render:', event)
debugger
},
renderTriggered(event) {
console.log('Re-render triggered by:', event)
debugger
}
}
```
**Debug event properties:**
```javascript
// The event object contains:
{
effect: ReactiveEffect, // The effect being debugged
target: object, // The reactive object
type: 'get' | 'set' | 'add' | 'delete' | 'clear',
key: string | symbol, // The property being accessed/mutated
oldValue: any, // Previous value (for onTrigger)
newValue: any // New value (for onTrigger)
}
```
## Reference
- [Vue.js Reactivity in Depth - Debugging](https://vuejs.org/guide/extras/reactivity-in-depth.html#reactivity-debugging)
- [Vue.js computed() API](https://vuejs.org/api/reactivity-core.html#computed)
- [Vue.js onRenderTracked()](https://vuejs.org/api/composition-api-lifecycle.html#onrendertracked)
@@ -0,0 +1,149 @@
---
title: Use markRaw() for Objects That Should Never Be Reactive
impact: MEDIUM
impactDescription: Library instances, DOM nodes, and complex objects cause overhead and bugs when wrapped in Vue proxies
type: efficiency
tags: [vue3, reactivity, markRaw, performance, external-libraries, dom]
---
# Use markRaw() for Objects That Should Never Be Reactive
**Impact: MEDIUM** - Vue's `markRaw()` tells the reactivity system to never wrap an object in a Proxy. Use it for library instances, DOM nodes, class instances with internal state, and complex objects that Vue shouldn't track. This prevents unnecessary proxy overhead and avoids subtle bugs from double-proxying.
Without `markRaw()`, placing these objects inside reactive state causes Vue to wrap them in Proxies, which can break library internals, cause identity issues, and waste memory on objects that don't need change tracking.
## Task Checklist
- [ ] Use `markRaw()` for third-party library instances (maps, charts, editors)
- [ ] Use `markRaw()` for DOM elements stored in reactive state
- [ ] Use `markRaw()` for class instances that manage their own state
- [ ] Use `markRaw()` for large static data that will never change
- [ ] Remember: markRaw only affects the root level - nested objects may still be proxied
**Incorrect:**
```javascript
import { reactive, ref } from 'vue'
import mapboxgl from 'mapbox-gl'
import * as monaco from 'monaco-editor'
// WRONG: Library instances wrapped in Proxy
const state = reactive({
map: new mapboxgl.Map({ container: 'map' }), // Proxied!
editor: monaco.editor.create(element, {}), // Proxied!
})
// Problems:
// 1. Library's internal this references may break
// 2. Unnecessary memory overhead
// 3. Methods may not work correctly through proxy
// 4. Performance degradation
// WRONG: DOM elements in reactive state
const elements = reactive({
container: document.getElementById('app'), // Proxied DOM node!
})
```
**Correct:**
```javascript
import { reactive, markRaw, shallowRef } from 'vue'
import mapboxgl from 'mapbox-gl'
import * as monaco from 'monaco-editor'
// CORRECT: Mark library instances as raw
const state = reactive({
map: markRaw(new mapboxgl.Map({ container: 'map' })),
editor: markRaw(monaco.editor.create(element, {})),
})
// CORRECT: Or use shallowRef for mutable references
const map = shallowRef(null)
onMounted(() => {
map.value = markRaw(new mapboxgl.Map({ container: 'map' }))
})
// CORRECT: Large static data
const geoJsonData = markRaw(await fetch('/huge-geojson.json').then(r => r.json()))
const state = reactive({
mapData: geoJsonData // Won't be proxied
})
```
**Class instances with internal state:**
```javascript
import { markRaw, reactive } from 'vue'
class WebSocketManager {
constructor(url) {
this.socket = new WebSocket(url)
this.listeners = new Map()
}
on(event, callback) {
this.listeners.set(event, callback)
}
}
// CORRECT: Mark class instance
const wsManager = markRaw(new WebSocketManager('ws://example.com'))
const state = reactive({
connection: wsManager // Won't be proxied
})
// Can still use the instance normally
state.connection.on('message', handleMessage)
```
**Gotcha: markRaw only affects root level:**
```javascript
import { markRaw, reactive } from 'vue'
const rawObject = markRaw({
nested: { value: 1 } // This nested object is NOT marked raw
})
const state = reactive({
data: rawObject
})
// rawObject itself won't be proxied
// But if you access nested objects through a reactive parent:
const container = reactive({ raw: rawObject })
// container.raw.nested might still be proxied in some cases
// SAFER: Use shallowRef for the container
import { shallowRef } from 'vue'
const safeContainer = shallowRef(rawObject)
```
**Combining with shallowRef for best results:**
```javascript
import { shallowRef, markRaw, onMounted, onUnmounted } from 'vue'
// Pattern: shallowRef + markRaw for external library instances
export function useMapbox(containerId) {
const map = shallowRef(null)
onMounted(() => {
const instance = new mapboxgl.Map({
container: containerId,
style: 'mapbox://styles/mapbox/streets-v11'
})
// Mark raw to prevent any proxy wrapping
map.value = markRaw(instance)
})
onUnmounted(() => {
map.value?.remove()
})
return { map }
}
```
## Reference
- [Vue.js markRaw() API](https://vuejs.org/api/reactivity-advanced.html#markraw)
- [Vue.js Reducing Reactivity Overhead](https://vuejs.org/guide/best-practices/performance.html#reduce-reactivity-overhead-for-large-immutable-structures)
- [Vue.js Reactivity in Depth](https://vuejs.org/guide/extras/reactivity-in-depth.html)
@@ -0,0 +1,96 @@
---
title: Avoid Comparing Reactive Objects with === Operator
impact: HIGH
impactDescription: Reactive proxies have different identity than original objects - comparison bugs are silent and hard to debug
type: gotcha
tags: [vue3, reactivity, proxy, comparison, debugging, identity]
---
# Avoid Comparing Reactive Objects with === Operator
**Impact: HIGH** - Vue's `reactive()` returns a Proxy wrapper that has a different identity than the original object. Using `===` to compare reactive objects can lead to silent bugs where comparisons unexpectedly return `false`.
When you wrap an object with `reactive()`, the returned proxy is NOT equal to the original object. Additionally, accessing nested objects from a reactive object returns new proxy wrappers each time, which can cause identity comparison issues.
## Task Checklist
- [ ] Never compare reactive object instances with `===` directly
- [ ] Use unique identifiers (ID, UUID) for object comparison instead
- [ ] Use `toRaw()` on both sides when identity comparison is absolutely necessary
- [ ] Consider using primitive identifiers from database records for comparison
**Incorrect:**
```javascript
import { reactive } from 'vue'
const original = { id: 1, name: 'Item' }
const state = reactive(original)
// BUG: Always returns false - proxy !== original
if (state === original) {
console.log('Same object') // Never executes
}
// BUG: Nested object comparison fails
const items = reactive([{ id: 1 }, { id: 2 }])
const item = items[0]
// Later...
if (items[0] === item) {
// May or may not work depending on Vue's proxy caching
}
// BUG: Comparing items from different reactive sources
const listA = reactive([{ id: 1 }])
const listB = reactive([{ id: 1 }])
if (listA[0] === listB[0]) {
// Never true, even though they represent the same data
}
```
**Correct:**
```javascript
import { reactive, toRaw } from 'vue'
const original = { id: 1, name: 'Item' }
const state = reactive(original)
// CORRECT: Use toRaw() for identity comparison
if (toRaw(state) === original) {
console.log('Same underlying object') // Works!
}
// BEST: Use unique identifiers instead
const items = reactive([
{ id: 'uuid-1', name: 'Item 1' },
{ id: 'uuid-2', name: 'Item 2' }
])
function findItem(targetId) {
return items.find(item => item.id === targetId)
}
function isSelected(item) {
return selectedId.value === item.id // Compare IDs, not objects
}
// CORRECT: For Set/Map operations, use primitive keys
const selectedIds = reactive(new Set())
selectedIds.add(item.id) // Use ID, not object
selectedIds.has(item.id) // Check by ID
```
```javascript
// When you must compare objects, use toRaw on both sides
import { toRaw, isReactive } from 'vue'
function areEqual(a, b) {
const rawA = isReactive(a) ? toRaw(a) : a
const rawB = isReactive(b) ? toRaw(b) : b
return rawA === rawB
}
```
## Reference
- [Vue.js Reactivity in Depth](https://vuejs.org/guide/extras/reactivity-in-depth.html)
- [Vue.js toRaw() API](https://vuejs.org/api/reactivity-advanced.html#toraw)
@@ -0,0 +1,166 @@
---
title: Understand Reactive Updates are Batched Per Event Loop Tick
impact: MEDIUM
impactDescription: Multiple synchronous reactive changes are batched - watchers only see the final value, not intermediate states
type: gotcha
tags: [vue3, reactivity, batching, event-loop, watchers, nextTick]
---
# Understand Reactive Updates are Batched Per Event Loop Tick
**Impact: MEDIUM** - Vue batches multiple reactive state changes that happen synchronously within the same event loop tick. Watchers and computed properties only see the final state, not intermediate values. This is an optimization, but it can be surprising if you expect watchers to fire for each individual change.
Understanding this behavior is essential for debugging scenarios where you expect to observe every state transition.
## Task Checklist
- [ ] Understand watchers fire once per tick with final value, not for each mutation
- [ ] Use `nextTick()` if you need to ensure DOM updates between state changes
- [ ] Use `flush: 'sync'` on watchers only if you absolutely need immediate execution
- [ ] For intermediate value tracking, consider logging or explicit state snapshots
**Example of batching behavior:**
```javascript
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newValue) => {
console.log('Count changed to:', newValue)
})
// Multiple synchronous changes in the same tick
function multipleUpdates() {
count.value = 1
count.value = 2
count.value = 3
count.value = 4
}
multipleUpdates()
// Console output: "Count changed to: 4"
// NOT: 1, 2, 3, 4 - only the final value is observed!
```
**The console logs you WON'T see:**
```javascript
const items = reactive([])
watch(items, (newItems) => {
console.log('Items count:', newItems.length)
})
// Batch of changes
items.push('a') // length: 1
items.push('b') // length: 2
items.push('c') // length: 3
// Output: "Items count: 3"
// You won't see 1, 2, 3 logged separately
```
**Using flush: 'sync' for immediate watching (use with caution):**
```javascript
import { ref, watch } from 'vue'
const count = ref(0)
// Sync watcher fires immediately on each change
watch(count, (newValue) => {
console.log('Immediate:', newValue)
}, { flush: 'sync' })
count.value = 1 // Logs: "Immediate: 1"
count.value = 2 // Logs: "Immediate: 2"
count.value = 3 // Logs: "Immediate: 3"
// WARNING: flush: 'sync' can cause performance issues
// and creates less predictable behavior. Avoid if possible.
```
**Using nextTick to separate batches:**
```javascript
import { ref, watch, nextTick } from 'vue'
const count = ref(0)
watch(count, (newValue) => {
console.log('Count:', newValue)
})
async function separatedUpdates() {
count.value = 1
await nextTick() // Force flush
// Output: "Count: 1"
count.value = 2
await nextTick()
// Output: "Count: 2"
count.value = 3
// Output: "Count: 3"
}
```
**Practical example - form validation:**
```javascript
const formData = reactive({
email: '',
password: ''
})
const validationErrors = ref([])
// This watcher only fires once, with final form state
watch(formData, (data) => {
// Runs once after all fields are updated
validateForm(data)
}, { deep: true })
// When user submits, you might update multiple fields
function populateFromSavedData(saved) {
formData.email = saved.email
formData.password = saved.password
// Validation runs once with both fields set
}
```
**When batching helps performance:**
```javascript
// Without batching, this would trigger 1000 watcher/render cycles
const list = reactive([])
function addManyItems() {
for (let i = 0; i < 1000; i++) {
list.push(i)
}
}
// With batching: renders once with all 1000 items
// Without batching: would render 1000 times!
```
**Debugging intermediate states:**
```javascript
// If you need to observe every change for debugging:
import { ref, watch } from 'vue'
const count = ref(0)
// Method 1: Sync watcher (not recommended for production)
watch(count, (val) => console.log('DEBUG:', val), { flush: 'sync' })
// Method 2: Track history manually
const history = []
const originalSet = count.value
Object.defineProperty(count, 'value', {
set(val) {
history.push(val)
originalSet.call(this, val)
}
})
```
## Reference
- [Vue.js Reactivity in Depth](https://vuejs.org/guide/extras/reactivity-in-depth.html)
- [Vue.js Watchers - Callback Flush Timing](https://vuejs.org/guide/essentials/watchers.html#callback-flush-timing)
- [Vue.js nextTick()](https://vuejs.org/api/general.html#nexttick)
@@ -0,0 +1,61 @@
---
title: Always Use .value When Accessing ref() in JavaScript
impact: HIGH
impactDescription: Forgetting .value causes silent failures and bugs in reactive state updates
type: capability
tags: [vue3, reactivity, ref, composition-api]
---
# Always Use .value When Accessing ref() in JavaScript
**Impact: HIGH** - Forgetting `.value` causes silent failures where state updates don't trigger reactivity, leading to hard-to-debug issues.
When using `ref()` in Vue 3's Composition API, the reactive value is wrapped in an object and must be accessed via `.value` in JavaScript code. However, in templates, Vue automatically unwraps refs so `.value` is not needed there. This inconsistency is a common source of bugs.
## Task Checklist
- [ ] Always use `.value` when reading or writing ref values in `<script>` or `.js`/`.ts` files
- [ ] Never use `.value` in `<template>` - Vue unwraps refs automatically there
- [ ] When passing refs to functions, decide whether to pass the ref object or `.value`
- [ ] Use IDE/TypeScript to catch missing `.value` errors early
**Incorrect:**
```javascript
import { ref } from 'vue'
const count = ref(0)
// These do NOT work as expected
count++ // Tries to increment the ref object, not the value
count = 5 // Reassigns the variable, loses reactivity
console.log(count) // Logs "[object Object]", not the number
const items = ref([1, 2, 3])
items.push(4) // Error: push is not a function
```
**Correct:**
```javascript
import { ref } from 'vue'
const count = ref(0)
// Always use .value in JavaScript
count.value++ // Correctly increments to 1
count.value = 5 // Correctly sets value to 5
console.log(count.value) // Logs "5"
const items = ref([1, 2, 3])
items.value.push(4) // Correctly adds 4 to the array
```
```vue
<template>
<!-- In templates, NO .value needed - Vue unwraps automatically -->
<p>{{ count }}</p>
<button @click="count++">Increment</button>
</template>
```
## Reference
- [Vue.js Reactivity Fundamentals - ref()](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#ref)
@@ -0,0 +1,81 @@
---
title: Refs in Arrays and Collections Require .value
impact: MEDIUM
impactDescription: Refs inside reactive arrays, Maps, or Sets are NOT auto-unwrapped like in reactive objects
type: capability
tags: [vue3, reactivity, ref, arrays, collections, unwrapping]
---
# Refs in Arrays and Collections Require .value
**Impact: MEDIUM** - Unlike when a ref is a property of a reactive object, refs inside reactive arrays, Maps, and Sets are NOT automatically unwrapped. You must access them with `.value`, and forgetting this leads to silent bugs.
Vue only auto-unwraps refs when they are properties of reactive objects. When refs are elements in arrays or values in Maps/Sets, they remain as ref objects and require explicit `.value` access.
## Task Checklist
- [ ] Always use `.value` when accessing refs stored in reactive arrays
- [ ] Always use `.value` when accessing refs stored in reactive Maps or Sets
- [ ] Consider storing plain values instead of refs in collections to avoid confusion
- [ ] Be aware of this when iterating over arrays containing refs
**Incorrect:**
```javascript
import { ref, reactive } from 'vue'
const books = reactive([ref('Vue 3 Guide')])
const counts = reactive(new Map([['clicks', ref(0)]]))
// WRONG: Refs in arrays are NOT unwrapped
console.log(books[0]) // Ref object, not 'Vue 3 Guide'
books[0] = 'New Title' // Replaces the ref, doesn't update it!
// WRONG: Refs in Maps are NOT unwrapped
console.log(counts.get('clicks')) // Ref object, not 0
counts.get('clicks')++ // Does nothing useful
```
**Correct:**
```javascript
import { ref, reactive } from 'vue'
const books = reactive([ref('Vue 3 Guide')])
const counts = reactive(new Map([['clicks', ref(0)]]))
// CORRECT: Use .value for refs in arrays
console.log(books[0].value) // 'Vue 3 Guide'
books[0].value = 'New Title' // Updates the ref's value
// CORRECT: Use .value for refs in Maps
console.log(counts.get('clicks').value) // 0
counts.get('clicks').value++ // Increments to 1
```
```javascript
// ALTERNATIVE: Just store plain values in collections (simpler)
const books = reactive(['Vue 3 Guide', 'Vuex Handbook'])
const counts = reactive(new Map([['clicks', 0]]))
// No .value needed - but changes to individual items aren't independently reactive
console.log(books[0]) // 'Vue 3 Guide'
console.log(counts.get('clicks')) // 0
// Mutations still trigger reactivity through the reactive wrapper
books[0] = 'New Title' // Works
counts.set('clicks', counts.get('clicks') + 1) // Works
```
```vue
<template>
<!-- In templates, refs in arrays also need special handling -->
<div v-for="(book, index) in books" :key="index">
<!-- If book is a ref, you'd need: -->
{{ book.value }}
<!-- Or use computed to unwrap them first -->
</div>
</template>
```
## Reference
- [Vue.js Reactivity Fundamentals - Caveat in Arrays and Collections](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#caveat-in-arrays-and-collections)
@@ -0,0 +1,151 @@
---
title: Do Not Rely on Internal VNode Properties
impact: MEDIUM
impactDescription: Using undocumented vnode properties causes code to break on Vue updates
type: gotcha
tags: [vue3, render-function, vnode, internal-api]
---
# Do Not Rely on Internal VNode Properties
**Impact: MEDIUM** - The `VNode` interface contains many internal properties used by Vue's rendering system. Relying on any properties other than the documented public ones will cause your code to break when Vue's internal implementation changes.
Only use the documented vnode properties: `type`, `props`, `children`, and `key`. All other properties are internal implementation details that may change without notice between Vue versions.
## Task Checklist
- [ ] Only access documented vnode properties: `type`, `props`, `children`, `key`
- [ ] Never access properties like `el`, `component`, `shapeFlag`, `patchFlag`, etc.
- [ ] If you need DOM element access, use template refs instead
- [ ] Treat vnodes as opaque data structures for rendering, not inspection
**Incorrect:**
```javascript
import { h } from 'vue'
export default {
setup(props, { slots }) {
return () => {
const slotContent = slots.default?.()
// WRONG: Accessing internal properties
if (slotContent?.[0]?.el) {
// el is an internal property
console.log(slotContent[0].el.tagName)
}
// WRONG: Using shapeFlag internal property
if (slotContent?.[0]?.shapeFlag & 1) {
// This is internal implementation
}
return h('div', slotContent)
}
}
}
```
```javascript
// WRONG: Inspecting component instance via vnode
const vnode = h(MyComponent)
console.log(vnode.component) // Internal property
console.log(vnode.appContext) // Internal property
```
**Correct:**
```javascript
import { h } from 'vue'
export default {
setup(props, { slots }) {
return () => {
const slotContent = slots.default?.()
// CORRECT: Only use documented properties
if (slotContent?.[0]) {
const vnode = slotContent[0]
console.log(vnode.type) // Safe: element type or component
console.log(vnode.props) // Safe: props object
console.log(vnode.children) // Safe: children
console.log(vnode.key) // Safe: key prop
}
return h('div', slotContent)
}
}
}
```
```javascript
import { h, ref, onMounted } from 'vue'
export default {
setup() {
// CORRECT: Use template refs for DOM access
const divRef = ref(null)
onMounted(() => {
// Safe way to access DOM element
console.log(divRef.value.tagName)
})
return () => h('div', { ref: divRef }, 'Content')
}
}
```
## Documented VNode Properties
| Property | Type | Description |
|----------|------|-------------|
| `type` | `string \| Component` | Element tag name or component definition |
| `props` | `object \| null` | Props passed to the vnode |
| `children` | `any` | Child vnodes, text, or slots |
| `key` | `string \| number \| null` | Key for list rendering |
## Safe VNode Inspection Patterns
```javascript
import { h, isVNode } from 'vue'
export default {
setup(props, { slots }) {
return () => {
const children = slots.default?.() || []
// Safe: Check if something is a vnode
children.forEach(child => {
if (isVNode(child)) {
// Safe: Check vnode type
if (typeof child.type === 'string') {
console.log('Element:', child.type)
} else if (typeof child.type === 'object') {
console.log('Component:', child.type.name)
}
// Safe: Read props
if (child.props?.class) {
console.log('Has class:', child.props.class)
}
}
})
return h('div', children)
}
}
}
```
## Why This Matters
Vue's internal vnode structure may change for:
- Performance optimizations
- New feature implementations
- Bug fixes
- Tree-shaking improvements
Code relying on internal properties will break silently or throw errors when upgrading Vue versions. The documented properties are part of Vue's public API and are guaranteed to remain stable.
## Reference
- [Vue.js Render Function APIs](https://vuejs.org/api/render-function.html)
- [Vue.js Render Functions - The Virtual DOM](https://vuejs.org/guide/extras/render-function.html#the-virtual-dom)
@@ -0,0 +1,133 @@
---
title: VNodes Must Be Unique in Render Functions
impact: HIGH
impactDescription: Reusing vnode references causes rendering bugs and unexpected behavior
type: gotcha
tags: [vue3, render-function, vnode, composition-api]
---
# VNodes Must Be Unique in Render Functions
**Impact: HIGH** - Reusing the same vnode reference multiple times in a render function tree causes rendering bugs, where only one instance appears or updates behave unexpectedly.
Every vnode in a component's render tree must be unique. You cannot use the same vnode object multiple times. If you need to render the same element multiple times, create each vnode separately using a factory function or by calling `h()` in a loop.
## Task Checklist
- [ ] Never store a vnode in a variable and use it multiple times in the same tree
- [ ] Use a factory function or `.map()` to create multiple similar vnodes
- [ ] Each `h()` call creates a new vnode, so call it for each instance needed
- [ ] Be especially careful when extracting vnode creation into helper functions
**Incorrect:**
```javascript
import { h } from 'vue'
export default {
setup() {
return () => {
// WRONG: Same vnode reference used twice
const p = h('p', 'Hello')
return h('div', [p, p]) // Bug! Duplicate vnode reference
}
}
}
```
```javascript
import { h } from 'vue'
export default {
setup() {
return () => {
// WRONG: Reusing vnode in different parts of tree
const icon = h('span', { class: 'icon' }, '★')
return h('div', [
h('button', [icon, ' Save']), // Uses icon
h('button', [icon, ' Delete']) // Reuses same icon - Bug!
])
}
}
}
```
**Correct:**
```javascript
import { h } from 'vue'
export default {
setup() {
return () => {
// CORRECT: Create new vnode for each use
return h('div', [
h('p', 'Hello'),
h('p', 'Hello')
])
}
}
}
```
```javascript
import { h } from 'vue'
export default {
setup() {
return () => {
// CORRECT: Factory function creates new vnode each time
const createIcon = () => h('span', { class: 'icon' }, '★')
return h('div', [
h('button', [createIcon(), ' Save']),
h('button', [createIcon(), ' Delete'])
])
}
}
}
```
```javascript
import { h } from 'vue'
export default {
setup() {
return () => {
// CORRECT: Using map to create multiple vnodes
return h('div',
Array.from({ length: 20 }).map(() => h('p', 'Hello'))
)
}
}
}
```
```javascript
import { h } from 'vue'
export default {
setup() {
const items = ['Apple', 'Banana', 'Cherry']
return () => h('ul',
// CORRECT: Each iteration creates a new vnode
items.map((item, index) =>
h('li', { key: index }, item)
)
)
}
}
```
## Why VNodes Must Be Unique
VNodes are lightweight JavaScript objects that Vue's virtual DOM algorithm uses for diffing and patching. When the same vnode reference appears multiple times:
- Vue cannot differentiate between the instances
- The diffing algorithm produces incorrect results
- Only one instance may render, or updates may corrupt the DOM
Each vnode maintains its own identity and position in the tree, which is essential for:
- Correct DOM patching during updates
- Proper lifecycle hook execution
- Accurate key-based reconciliation in lists
## Reference
- [Vue.js Render Functions - Vnodes Must Be Unique](https://vuejs.org/guide/extras/render-function.html#vnodes-must-be-unique)
@@ -0,0 +1,148 @@
---
title: Import h Globally in Vue 3 Render Functions
impact: HIGH
impactDescription: Vue 3 requires explicit h import; using Vue 2 patterns causes runtime errors
type: gotcha
tags: [vue3, render-function, migration, h, vnode, breaking-change]
---
# Import h Globally in Vue 3 Render Functions
**Impact: HIGH** - In Vue 2, the `h` function (createElement) was passed as an argument to render functions. In Vue 3, `h` must be explicitly imported from 'vue'. Using Vue 2 patterns causes runtime errors.
## Task Checklist
- [ ] Import `h` from 'vue' at the top of files using render functions
- [ ] Remove the `h` parameter from render function signatures
- [ ] Update all render functions when migrating from Vue 2
**Incorrect (Vue 2 pattern - broken in Vue 3):**
```js
// WRONG: Vue 2 pattern - h is not passed as argument in Vue 3
export default {
render(h) { // h is undefined in Vue 3!
return h('div', [
h('span', 'Hello')
])
}
}
// WRONG: Using createElement alias from Vue 2
export default {
render(createElement) { // Also undefined
return createElement('div', 'Hello')
}
}
```
**Correct (Vue 3 pattern):**
```js
// CORRECT: Import h from vue
import { h } from 'vue'
export default {
render() {
return h('div', [
h('span', 'Hello')
])
}
}
```
## With Composition API
```js
import { h, ref } from 'vue'
export default {
setup() {
const count = ref(0)
// Return a render function from setup
return () => h('div', [
h('button', { onClick: () => count.value++ }, `Count: ${count.value}`)
])
}
}
```
## With script setup (Not Recommended)
```vue
<script setup>
import { h, ref } from 'vue'
const count = ref(0)
// Cannot return render function from script setup
// Must use a separate render option or template
</script>
<!-- script setup typically uses templates, not render functions -->
<template>
<div>
<button @click="count++">Count: {{ count }}</button>
</div>
</template>
```
If you need render functions with `<script setup>`, use the `render` option:
```vue
<script>
import { h, ref } from 'vue'
export default {
setup() {
const count = ref(0)
return () => h('button', { onClick: () => count.value++ }, count.value)
}
}
</script>
```
## Component Resolution Change
In Vue 3, you must also explicitly resolve components:
**Incorrect:**
```js
// Vue 2: Could use string names for registered components
render(h) {
return h('my-component', { props: { value: 1 } })
}
```
**Correct:**
```js
import { h, resolveComponent } from 'vue'
export default {
render() {
// Must resolve component by name
const MyComponent = resolveComponent('my-component')
return h(MyComponent, { value: 1 })
}
}
// Or import the component directly (preferred)
import { h } from 'vue'
import MyComponent from './MyComponent.vue'
export default {
render() {
return h(MyComponent, { value: 1 })
}
}
```
## Why This Changed
Vue 3's `h` is globally importable to:
1. Enable tree-shaking (unused features can be removed)
2. Support better TypeScript inference
3. Allow use outside of component context
## Reference
- [Vue 3 Migration Guide - Render Function API](https://v3-migration.vuejs.org/breaking-changes/render-function-api.html)
- [Vue.js Render Functions & JSX](https://vuejs.org/guide/extras/render-function.html)
@@ -0,0 +1,148 @@
---
title: Return Render Function from setup(), Not Direct VNodes
impact: HIGH
impactDescription: Returning a vnode directly from setup makes it static; returning a function enables reactive updates
type: gotcha
tags: [vue3, render-function, composition-api, setup, reactivity]
---
# Return Render Function from setup(), Not Direct VNodes
**Impact: HIGH** - When using render functions with the Composition API, you must return a function that returns vnodes, not the vnodes directly. Returning vnodes directly creates a static render that never updates when reactive state changes.
## Task Checklist
- [ ] Always return an arrow function from setup() when using render functions
- [ ] Never return h() calls directly from setup()
- [ ] Ensure reactive values are accessed inside the returned function
**Incorrect:**
```js
import { h, ref } from 'vue'
export default {
setup() {
const count = ref(0)
const increment = () => count.value++
// WRONG: Returns a static vnode, created once
// Clicking the button updates count.value, but the DOM never changes!
return h('div', [
h('p', `Count: ${count.value}`), // Captures count.value at setup time (0)
h('button', { onClick: increment }, 'Increment')
])
}
}
```
**Correct:**
```js
import { h, ref } from 'vue'
export default {
setup() {
const count = ref(0)
const increment = () => count.value++
// CORRECT: Returns a render function
// Vue calls this function on every reactive update
return () => h('div', [
h('p', `Count: ${count.value}`), // Re-evaluated each render
h('button', { onClick: increment }, 'Increment')
])
}
}
```
## Why This Happens
```js
// What Vue does internally:
// WRONG approach - setup runs once:
const result = setup()
// result is a vnode { type: 'div', children: [...] }
// Vue renders this once, then has no way to re-render
// CORRECT approach - setup returns a function:
const renderFn = setup()
// renderFn is () => h('div', ...)
// Vue calls renderFn() on mount
// Vue calls renderFn() again whenever dependencies change
```
## Common Mistake: Mixing Template and Render Function
```vue
<script setup>
import { h, ref } from 'vue'
const count = ref(0)
// WRONG: Can't use render functions in script setup with templates
// This h() call does nothing
const node = h('div', count.value)
</script>
<template>
<!-- Template is used, render function is ignored -->
<div>{{ count }}</div>
</template>
```
If you need a render function with Composition API, don't use `<script setup>`:
```vue
<script>
import { h, ref } from 'vue'
export default {
setup() {
const count = ref(0)
return () => h('div', count.value)
}
}
</script>
<!-- No template - render function is used -->
```
## Exposing Values While Using Render Functions
```js
import { h, ref } from 'vue'
export default {
setup(props, { expose }) {
const count = ref(0)
const reset = () => { count.value = 0 }
// Expose methods for parent refs
expose({ reset })
// Still return the render function
return () => h('div', count.value)
}
}
```
## With Slots
```js
import { h, ref } from 'vue'
export default {
setup(props, { slots }) {
const count = ref(0)
return () => h('div', [
h('p', `Count: ${count.value}`),
// Slots must also be called inside the render function
slots.default?.()
])
}
}
```
## Reference
- [Vue.js Render Functions with Composition API](https://vuejs.org/guide/extras/render-function.html#render-functions-jsx)
- [Vue.js Composition API setup()](https://vuejs.org/api/composition-api-setup.html)
@@ -0,0 +1,168 @@
---
title: Pass Slots as Functions in Render Functions, Not Direct Children
impact: HIGH
impactDescription: Passing slot content incorrectly causes slots to not render or be treated as props
type: gotcha
tags: [vue3, render-function, slots, children, vnode]
---
# Pass Slots as Functions in Render Functions, Not Direct Children
**Impact: HIGH** - When creating component vnodes with `h()`, children must be passed as slot functions, not as direct children. Passing children directly may cause them to be interpreted as props or fail to render.
## Task Checklist
- [ ] Pass slot content as functions: `{ default: () => [...] }`
- [ ] Use `null` for props when only passing slots to avoid misinterpretation
- [ ] For default slot only, a single function can be passed directly
- [ ] For named slots, use an object with slot function properties
**Incorrect:**
```js
import { h } from 'vue'
import MyComponent from './MyComponent.vue'
// WRONG: Children array may be misinterpreted
h(MyComponent, [
h('span', 'Slot content') // May not render as expected
])
// WRONG: Named slots as direct properties
h(MyComponent, {
header: h('h1', 'Title'), // This is a prop, not a slot!
default: h('p', 'Content') // This is also a prop
})
```
**Correct:**
```js
import { h } from 'vue'
import MyComponent from './MyComponent.vue'
// CORRECT: Default slot as function
h(MyComponent, null, {
default: () => h('span', 'Slot content')
})
// CORRECT: Single default slot shorthand
h(MyComponent, null, () => h('span', 'Slot content'))
// CORRECT: Named slots as functions
h(MyComponent, null, {
header: () => h('h1', 'Title'),
default: () => h('p', 'Content'),
footer: () => [
h('span', 'Footer item 1'),
h('span', 'Footer item 2')
]
})
// CORRECT: With props AND slots
h(MyComponent, { size: 'large' }, {
default: () => 'Button Text'
})
```
## Why Functions?
Slots in Vue 3 are functions for lazy evaluation:
```js
// Slots are called by the child component when needed
// This enables:
// 1. Scoped slots (passing data back)
// 2. Conditional rendering (slot not called if not used)
// 3. Proper reactivity tracking
h(MyList, { items }, {
// Scoped slot - receives data from child
item: ({ item, index }) => h('li', `${index}: ${item.name}`)
})
```
## The null Props Gotcha
When passing only slots, always use `null` for props:
```js
// WRONG: Slots object interpreted as props!
h(MyComponent, {
default: () => 'Hello'
})
// MyComponent receives: props.default = () => 'Hello'
// CORRECT: null signals "no props, next arg is slots"
h(MyComponent, null, {
default: () => 'Hello'
})
// MyComponent receives slot correctly
```
## Forwarding Slots from Parent
```js
export default {
setup(props, { slots }) {
return () => h(ChildComponent, null, {
// Forward all slots from parent
...slots,
// Or forward specific slots
default: slots.default,
header: slots.header
})
}
}
```
## Scoped Slots in Render Functions
```js
// Parent: Receives data from child via slot props
h(DataTable, { data: items }, {
row: (slotProps) => h('tr', [
h('td', slotProps.item.name),
h('td', slotProps.item.value)
])
})
// Child (DataTable): Calls slot with data
export default {
props: ['data'],
setup(props, { slots }) {
return () => h('table', [
h('tbody',
props.data.map(item =>
// Pass data to slot function
slots.row?.({ item })
)
)
])
}
}
```
## Common Patterns
```js
// Wrapper component forwarding slots
h('div', { class: 'wrapper' }, [
h(InnerComponent, null, slots)
])
// Conditional slot rendering
h('div', [
slots.header?.(), // Optional chaining - only render if slot provided
h('main', slots.default?.()),
slots.footer?.()
])
// Slot with fallback content
h('div', [
slots.default?.() ?? h('p', 'Default content when slot not provided')
])
```
## Reference
- [Vue.js Render Functions - Passing Slots](https://vuejs.org/guide/extras/render-function.html#passing-slots)
- [Vue.js Render Functions - Children](https://vuejs.org/guide/extras/render-function.html#children)
@@ -0,0 +1,231 @@
---
title: Use resolveComponent for String Component Names in Render Functions
impact: HIGH
impactDescription: String component names don't work in Vue 3 render functions; causes silent failures or runtime errors
type: gotcha
tags: [vue3, render-function, components, resolveComponent, migration]
---
# Use resolveComponent for String Component Names in Render Functions
**Impact: HIGH** - In Vue 2, render functions could use string names for globally or locally registered components. In Vue 3, you must either import components directly or use `resolveComponent()`. Using string names causes components to render as HTML elements or fail silently.
## Task Checklist
- [ ] Import components directly when possible (preferred)
- [ ] Use `resolveComponent()` for dynamically registered components
- [ ] Use `resolveDynamicComponent()` for `<component :is="">` equivalent
- [ ] Call `resolveComponent()` inside `setup()` or the render function
- [ ] Handle the case when component is not found
**Incorrect:**
```js
import { h } from 'vue'
export default {
render() {
// WRONG: String names don't resolve to components
return h('div', [
h('my-component', { value: 1 }), // Renders <my-component> HTML element!
h('router-link', { to: '/' }, 'Home') // Also fails
])
}
}
```
**Correct (Direct Import - Preferred):**
```js
import { h } from 'vue'
import MyComponent from './MyComponent.vue'
import { RouterLink } from 'vue-router'
export default {
render() {
return h('div', [
h(MyComponent, { value: 1 }),
h(RouterLink, { to: '/' }, () => 'Home')
])
}
}
```
**Correct (resolveComponent for Registered Components):**
```js
import { h, resolveComponent } from 'vue'
export default {
components: {
MyComponent: () => import('./MyComponent.vue')
},
setup() {
// Resolve inside setup - component context is available
const MyComponent = resolveComponent('MyComponent')
return () => h('div', [
h(MyComponent, { value: 1 })
])
}
}
// Or resolve inside render function
export default {
render() {
const MyComponent = resolveComponent('MyComponent')
const RouterLink = resolveComponent('RouterLink')
return h('div', [
h(MyComponent, { value: 1 }),
h(RouterLink, { to: '/' }, () => 'Home')
])
}
}
```
## When to Use Each Approach
| Approach | Use When |
|----------|----------|
| Direct Import | Component is known at build time (most common) |
| `resolveComponent()` | Component is registered globally or locally by name |
| `resolveComponent()` | Dynamic component selection from registered set |
## Handling Missing Components
```js
import { h, resolveComponent } from 'vue'
export default {
setup() {
// resolveComponent returns the component or the string name if not found
const DynamicComponent = resolveComponent('MaybeRegistered')
// Check if resolution succeeded
if (typeof DynamicComponent === 'string') {
console.warn(`Component "${DynamicComponent}" not found`)
}
return () => h(DynamicComponent, { value: 1 })
}
}
```
## Dynamic Component Selection
```js
import { h, resolveComponent, computed } from 'vue'
export default {
props: ['componentName'],
setup(props) {
// For truly dynamic components, resolve in render function
return () => {
const Component = resolveComponent(props.componentName)
return h(Component, { /* props */ })
}
}
}
```
For the equivalent of `<component :is="componentName">`, use `resolveDynamicComponent`:
```js
import { h, resolveDynamicComponent } from 'vue'
export default {
props: ['componentType'],
setup(props) {
return () => {
// Resolves string names, component objects, or built-in elements
const component = resolveDynamicComponent(props.componentType)
return h(component, { /* props */ })
}
}
}
```
## Practical Example: Tab Component
```js
import { h, resolveComponent, ref } from 'vue'
export default {
setup() {
const currentTab = ref('TabA')
const tabs = ['TabA', 'TabB', 'TabC']
return () => h('div', [
// Tab buttons
h('div', { class: 'tabs' },
tabs.map(tab =>
h('button', {
key: tab,
class: { active: currentTab.value === tab },
onClick: () => currentTab.value = tab
}, tab)
)
),
// Dynamic component based on current tab
h(resolveComponent(currentTab.value))
])
}
}
```
## Resolving Built-in Components
For built-in components like `<Transition>` or `<KeepAlive>`, import them directly from Vue:
```js
import { h, Transition, KeepAlive, Teleport, Suspense } from 'vue'
export default {
setup() {
return () => h(Transition, { name: 'fade' }, () =>
h('div', 'Content')
)
}
}
```
## Resolving Directives
Similar pattern for custom directives:
```js
import { h, resolveDirective, withDirectives } from 'vue'
export default {
render() {
const vFocus = resolveDirective('focus')
return withDirectives(
h('input', { type: 'text' }),
[[vFocus]]
)
}
}
```
## Migration from Vue 2
```js
// Vue 2 (worked with registered components)
render(h) {
return h('my-component', { props: { value: 1 } })
}
// Vue 3 (must resolve or import)
import { h, resolveComponent } from 'vue'
render() {
const MyComponent = resolveComponent('my-component')
return h(MyComponent, { value: 1 }) // Note: props go directly, not in 'props' key
}
```
## Reference
- [Vue 3 Migration - Render Function API](https://v3-migration.vuejs.org/breaking-changes/render-function-api.html)
- [Vue.js Render Function API - resolveComponent](https://vuejs.org/api/render-function.html#resolvecomponent)
@@ -0,0 +1,91 @@
---
title: Select Element iOS Bug - Always Include Disabled Placeholder Option
impact: HIGH
impactDescription: On iOS, users cannot select the first option if v-model initial value doesn't match any option
type: capability
tags: [vue3, v-model, forms, select, ios, mobile, accessibility]
---
# Select Element iOS Bug - Always Include Disabled Placeholder Option
**Impact: HIGH** - When a `<select>` element's v-model initial value doesn't match any option, iOS renders it as "unselected" and users CANNOT select the first item. iOS doesn't fire a change event when selecting an already-visually-selected option, leaving users stuck.
This is a platform-specific bug that only manifests on iOS Safari. Desktop browsers and Android handle this gracefully, making it easy to miss during development. The fix is simple: always include a disabled placeholder option.
## Task Checklist
- [ ] Always add a disabled placeholder option with empty value to select elements
- [ ] Ensure v-model initial value is empty string to match the placeholder
- [ ] Test select inputs on iOS devices or simulators
- [ ] Consider this for any user-facing forms, especially on mobile-first apps
**Problem - iOS users cannot select first option:**
```html
<script setup>
import { ref } from 'vue'
// Initial value is empty string, doesn't match any option
const selected = ref('')
</script>
<template>
<!-- PROBLEM: On iOS, "Apple" appears selected but user cannot actually select it -->
<!-- Tapping "Apple" does nothing because iOS doesn't fire change event -->
<select v-model="selected">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
<!-- selected remains '' even though "Apple" appears highlighted -->
</template>
```
**Solution - Add disabled placeholder option:**
```html
<script setup>
import { ref } from 'vue'
const selected = ref('') // Matches the placeholder option
</script>
<template>
<!-- CORRECT: Disabled placeholder ensures user must actively select -->
<select v-model="selected">
<option disabled value="">Please select a fruit</option>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
</template>
```
```html
<!-- Variant with required attribute for form validation -->
<select v-model="selected" required>
<option disabled value="">-- Select an option --</option>
<option value="a">Option A</option>
<option value="b">Option B</option>
</select>
```
```html
<!-- If you MUST have a pre-selected default, set the initial value to match -->
<script setup>
import { ref } from 'vue'
// Set initial value to match an actual option
const country = ref('us') // Pre-selects "United States"
</script>
<template>
<select v-model="country">
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
<option value="ca">Canada</option>
</select>
</template>
```
## Reference
- [Vue.js Form Input Bindings - Select](https://vuejs.org/guide/essentials/forms.html#select)
@@ -0,0 +1,157 @@
---
title: Self-Referencing Components Use Filename as Implicit Name
impact: LOW
impactDescription: Understanding this avoids confusion with recursive components
type: gotcha
tags: [vue3, component-registration, self-reference, recursive-components, sfc]
---
# Self-Referencing Components Use Filename as Implicit Name
**Impact: LOW** - In Single-File Components (SFC), a component can reference itself in its own template using its filename as the component name. This is useful for recursive components like tree structures or nested comments. However, this implicit registration has lower priority than explicitly imported components, which can cause confusion.
## Task Checklist
- [ ] Use the filename (without extension) to self-reference a component
- [ ] Be aware that imported components take precedence over self-reference
- [ ] For clarity in recursive components, consider explicit naming
**Example:**
```vue
<!-- TreeItem.vue -->
<script setup>
defineProps({
item: Object
})
</script>
<template>
<div class="tree-item">
<span>{{ item.name }}</span>
<!-- Self-reference using filename -->
<TreeItem
v-for="child in item.children"
:key="child.id"
:item="child"
/>
</div>
</template>
```
```vue
<!-- Comment.vue - recursive comments -->
<script setup>
defineProps({
comment: Object
})
</script>
<template>
<div class="comment">
<p>{{ comment.text }}</p>
<div class="replies" v-if="comment.replies?.length">
<!-- Self-reference for nested replies -->
<Comment
v-for="reply in comment.replies"
:key="reply.id"
:comment="reply"
/>
</div>
</div>
</template>
```
## Priority: Imports Override Self-Reference
```vue
<!-- FooBar.vue -->
<script setup>
// If you import a component named FooBar, it takes precedence
import FooBar from './different/FooBar.vue'
</script>
<template>
<!-- This renders the IMPORTED FooBar, not this file -->
<FooBar />
</template>
```
To explicitly self-reference when there's a naming conflict:
```vue
<!-- FooBar.vue -->
<script setup>
import OtherFooBar from './different/FooBar.vue'
// No way to explicitly import "self" in script setup
// Must rename the import to avoid conflict
</script>
<template>
<OtherFooBar />
<!-- FooBar still refers to self (this file) because
the import was aliased -->
<FooBar />
</template>
```
## Options API: Explicit Name Option
```vue
<!-- RecursiveList.vue -->
<script>
export default {
name: 'RecursiveList', // Explicit name for self-reference
props: {
items: Array
}
}
</script>
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
<RecursiveList v-if="item.children" :items="item.children" />
</li>
</ul>
</template>
```
## Common Use Cases for Self-Reference
1. **Tree structures** - File explorers, org charts
2. **Nested comments** - Reddit-style comment threads
3. **Menu navigation** - Recursive dropdown menus
4. **Category hierarchies** - Product categories, taxonomies
## Avoid Infinite Recursion
```vue
<!-- TreeNode.vue -->
<script setup>
defineProps({
node: Object,
maxDepth: { type: Number, default: 10 },
currentDepth: { type: Number, default: 0 }
})
</script>
<template>
<div class="node">
{{ node.name }}
<!-- Guard against infinite recursion -->
<template v-if="node.children && currentDepth < maxDepth">
<TreeNode
v-for="child in node.children"
:key="child.id"
:node="child"
:max-depth="maxDepth"
:current-depth="currentDepth + 1"
/>
</template>
</div>
</template>
```
## Reference
- [Vue.js Component Registration](https://vuejs.org/guide/components/registration.html)
@@ -0,0 +1,184 @@
---
title: SFC Script Block Must Use Default Export Only
impact: HIGH
impactDescription: Named exports in SFC script blocks will fail silently or cause build errors - Vue expects exactly one default export
type: gotcha
tags: [vue3, sfc, export, script-block, composition-api]
---
# SFC Script Block Must Use Default Export Only
**Impact: HIGH** - Vue Single-File Components expect exactly one default export from the `<script>` block. Using named exports for your component will cause build failures or runtime errors because Vue's tooling is designed to process a single default-exported component definition per `.vue` file.
## Task Checklist
- [ ] Always use `export default` in `<script>` blocks (Options API)
- [ ] Use `<script setup>` which handles exports automatically (Composition API)
- [ ] Move shared utilities to separate `.js`/`.ts` files, not the component's script block
- [ ] If you need to export types, use a separate `<script>` block alongside `<script setup>`
**Problematic Code:**
```vue
<!-- MyComponent.vue -->
<script>
// BAD: Named exports don't work for the component itself
export const MyComponent = {
data() {
return { count: 0 }
}
}
// BAD: Exporting multiple things from component script
export const CONSTANT = 42
export function helper() { }
</script>
<template>
<div>{{ count }}</div>
</template>
```
**Correct Code:**
```vue
<!-- MyComponent.vue - Options API -->
<script>
// GOOD: Single default export
export default {
data() {
return { count: 0 }
}
}
</script>
<template>
<div>{{ count }}</div>
</template>
```
```vue
<!-- MyComponent.vue - Composition API with script setup -->
<script setup>
// GOOD: No export needed, component is auto-exported
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<div>{{ count }}</div>
</template>
```
## Exporting Types Alongside Script Setup
For TypeScript, use a separate regular script block for type exports:
```vue
<script lang="ts">
// Regular script block for exports
export interface User {
id: number
name: string
}
export type Status = 'pending' | 'active' | 'inactive'
</script>
<script setup lang="ts">
// Setup script for component logic
import { ref } from 'vue'
const users = ref<User[]>([])
</script>
<template>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</template>
```
## Sharing Utilities Across Components
Don't put shared code in component script blocks. Create separate files:
```typescript
// utils/constants.ts
export const ITEMS_PER_PAGE = 20
export const API_BASE_URL = '/api/v1'
// utils/helpers.ts
export function formatDate(date: Date): string {
return date.toLocaleDateString()
}
export function formatCurrency(amount: number): string {
return `$${amount.toFixed(2)}`
}
```
```vue
<!-- ProductList.vue -->
<script setup>
// GOOD: Import shared utilities from external files
import { ITEMS_PER_PAGE } from '@/utils/constants'
import { formatCurrency } from '@/utils/helpers'
import { ref } from 'vue'
const products = ref([])
</script>
```
## Why This Restriction Exists
Vue's SFC compiler and build tools expect:
1. **One component per file**: The `.vue` file format is designed for single-component definitions
2. **Predictable structure**: Tools like Volar, vue-tsc, and bundler plugins assume default export
3. **Hot Module Replacement**: HMR relies on the single-component-per-file convention
```javascript
// How Vue tooling processes SFCs internally
import MyComponent from './MyComponent.vue'
// ^ Always expects the default export to be the component
```
## Common Mistake: Reusing Code via SFC Exports
```vue
<!-- BAD PATTERN: Trying to reuse code from components -->
<script>
// This won't work as expected
export const sharedLogic = () => { ... }
export default {
// component definition
}
</script>
```
Instead, use composables:
```typescript
// composables/useSharedLogic.ts
export function useSharedLogic() {
// Shared reactive logic
const state = ref(0)
const increment = () => state.value++
return { state, increment }
}
```
```vue
<!-- ComponentA.vue -->
<script setup>
import { useSharedLogic } from '@/composables/useSharedLogic'
const { state, increment } = useSharedLogic()
</script>
```
## Reference
- [Vue.js SFC Specification](https://vuejs.org/api/sfc-spec.html)
- [Vue.js Composition API - Composables](https://vuejs.org/guide/reusability/composables.html)
@@ -0,0 +1,156 @@
---
title: Use Deep Selectors for Styling Child Component Elements
impact: HIGH
impactDescription: Scoped styles cannot target elements inside child components without deep selectors, leading to silently broken styles
type: gotcha
tags: [vue3, sfc, scoped-css, deep-selector, child-components]
---
# Use Deep Selectors for Styling Child Component Elements
**Impact: HIGH** - When using scoped CSS in Vue SFCs, styles do not penetrate into child components. Without using deep selectors (`:deep()`), your styles will silently fail to apply to elements rendered by child components or third-party libraries.
## Task Checklist
- [ ] Use `:deep()` selector to style elements inside child components
- [ ] Never use deprecated `>>>` or `/deep/` selectors (Vue 3 only supports `:deep()`)
- [ ] Scope deep selectors to a parent class when possible to limit impact
- [ ] Consider using unscoped styles or CSS modules for heavily nested styling
**Problematic Code:**
```vue
<template>
<div class="container">
<ThirdPartyDatePicker />
</div>
</template>
<style scoped>
/* BAD: These styles won't apply to elements inside ThirdPartyDatePicker */
.container .date-input {
border-color: blue;
}
.container .calendar-popup {
background: white;
}
</style>
```
**Correct Code:**
```vue
<template>
<div class="container">
<ThirdPartyDatePicker />
</div>
</template>
<style scoped>
/* GOOD: Use :deep() to style child component elements */
.container :deep(.date-input) {
border-color: blue;
}
.container :deep(.calendar-popup) {
background: white;
}
/* Also correct: deep selector at root level */
:deep(.date-picker-wrapper) {
padding: 1rem;
}
</style>
```
## How Scoped CSS Works
Vue scoped CSS adds a unique data attribute to all elements in the component's template and appends it to CSS selectors:
```vue
<!-- Template output -->
<div class="container" data-v-7ba5bd90>
<!-- Child component elements DON'T get data-v-7ba5bd90 -->
<div class="date-input">...</div>
</div>
```
```css
/* Generated scoped CSS */
.container[data-v-7ba5bd90] .date-input[data-v-7ba5bd90] { ... }
/* ^ This won't match because .date-input doesn't have the attribute */
```
## Vue 3 Deep Selector Syntax
```vue
<style scoped>
/* Vue 3 recommended syntax */
.parent :deep(.child-class) {
color: red;
}
/* DEPRECATED - don't use these in Vue 3 */
.parent >>> .child-class { } /* Won't work in SCSS */
.parent /deep/ .child-class { } /* Deprecated */
.parent ::v-deep .child-class { } /* Old syntax */
</style>
```
## Scoping Deep Selectors for Safety
Always scope `:deep()` to a parent selector to limit its reach:
```vue
<style scoped>
/* BAD: Affects ALL .btn elements in child components globally */
:deep(.btn) {
background: blue;
}
/* GOOD: Only affects .btn inside .my-component */
.my-component :deep(.btn) {
background: blue;
}
</style>
```
## Child Component Root Element Exception
Note: A child component's root element IS affected by parent scoped CSS. This is intentional for layout purposes:
```vue
<!-- Parent.vue -->
<template>
<ChildComponent class="styled-child" />
</template>
<style scoped>
/* This WILL work - targets child's root element */
.styled-child {
margin: 1rem;
border: 1px solid gray;
}
</style>
```
## Performance Consideration
Using `:deep()` with element selectors can be slower:
```vue
<style scoped>
/* SLOWER: Element selector with deep */
.container :deep(p) {
color: red;
}
/* FASTER: Class selector with deep */
.container :deep(.paragraph) {
color: red;
}
</style>
```
## Reference
- [Vue.js Scoped CSS - Deep Selectors](https://vuejs.org/api/sfc-css-features.html#deep-selectors)
- [Vue Loader Scoped CSS](https://vue-loader.vuejs.org/guide/scoped-css.html)
@@ -0,0 +1,193 @@
---
title: Scoped CSS Does Not Apply to Dynamically Added Content
impact: HIGH
impactDescription: Programmatically inserted DOM elements won't receive scoped style data attributes, causing styles to fail silently
type: gotcha
tags: [vue3, sfc, scoped-css, dynamic-content, v-html]
---
# Scoped CSS Does Not Apply to Dynamically Added Content
**Impact: HIGH** - Vue's scoped CSS works by adding data attributes to elements at compile time. Content added dynamically at runtime (via `v-html`, JavaScript DOM manipulation, or third-party libraries) won't have these attributes, so scoped styles won't apply.
## Task Checklist
- [ ] For `v-html` content, use `:deep()` selectors or unscoped styles
- [ ] Avoid programmatic DOM manipulation; prefer Vue's reactive template system
- [ ] When DOM manipulation is unavoidable, use global styles with unique class prefixes
- [ ] Consider CSS modules for content that mixes static and dynamic elements
**Problematic Code:**
```vue
<script setup>
import { ref } from 'vue'
const htmlContent = ref('<p class="dynamic">This is dynamic content</p>')
</script>
<template>
<div class="container">
<div v-html="htmlContent"></div>
</div>
</template>
<style scoped>
/* BAD: Won't apply to the dynamic <p> element! */
.dynamic {
color: red;
font-weight: bold;
}
</style>
```
**Correct Code:**
```vue
<script setup>
import { ref } from 'vue'
const htmlContent = ref('<p class="dynamic">This is dynamic content</p>')
</script>
<template>
<div class="container">
<div v-html="htmlContent"></div>
</div>
</template>
<style scoped>
/* GOOD: Use :deep() for v-html content */
.container :deep(.dynamic) {
color: red;
font-weight: bold;
}
</style>
```
## Why This Happens
Vue scoped CSS adds a unique data attribute (e.g., `data-v-7ba5bd90`) to:
1. All elements in the component's template (at compile time)
2. All CSS selectors
```html
<!-- What Vue generates at compile time -->
<div class="container" data-v-7ba5bd90>
<div data-v-7ba5bd90>
<!-- v-html content is inserted at runtime WITHOUT the attribute -->
<p class="dynamic">This is dynamic content</p>
</div>
</div>
```
```css
/* Generated scoped CSS */
.dynamic[data-v-7ba5bd90] { color: red; }
/* ^ Won't match because the dynamic <p> doesn't have data-v-7ba5bd90 */
```
## Alternative: Global Styles with Unique Prefix
```vue
<script setup>
import { ref } from 'vue'
const htmlContent = ref('<p class="my-component-dynamic">Dynamic text</p>')
</script>
<template>
<div class="my-component">
<div v-html="htmlContent"></div>
</div>
</template>
<!-- Use unscoped styles with unique prefixes -->
<style>
.my-component .my-component-dynamic {
color: red;
}
</style>
```
## Programmatic DOM Manipulation
When using third-party libraries that manipulate the DOM:
```vue
<script setup>
import { ref, onMounted } from 'vue'
const editorRef = ref(null)
onMounted(() => {
// Third-party editor that injects its own DOM elements
initRichEditor(editorRef.value)
})
</script>
<template>
<div class="editor-wrapper">
<div ref="editorRef"></div>
</div>
</template>
<style scoped>
/* BAD: Won't reach injected editor elements */
.editor-toolbar { ... }
.editor-content { ... }
</style>
<style>
/* GOOD: Global styles scoped by parent class */
.editor-wrapper .editor-toolbar {
background: #f5f5f5;
}
.editor-wrapper .editor-content {
padding: 1rem;
}
</style>
```
## Best Practice: Prefer Reactive Templates
Instead of dynamic HTML, use Vue's reactive system when possible:
```vue
<script setup>
import { ref } from 'vue'
// BAD: Dynamic HTML that needs special style handling
const badHtml = ref('<span class="highlight">text</span>')
// GOOD: Reactive data that templates handle
const items = ref([
{ text: 'Item 1', isHighlighted: true },
{ text: 'Item 2', isHighlighted: false }
])
</script>
<template>
<!-- BAD -->
<div v-html="badHtml"></div>
<!-- GOOD: Scoped styles work normally -->
<ul>
<li
v-for="item in items"
:key="item.text"
:class="{ highlight: item.isHighlighted }"
>
{{ item.text }}
</li>
</ul>
</template>
<style scoped>
/* Works perfectly with reactive template */
.highlight {
background: yellow;
}
</style>
```
## Reference
- [Vue.js Scoped CSS](https://vuejs.org/api/sfc-css-features.html#scoped-css)
- [GitHub Issue: Scoped CSS not applied for programmatically added elements](https://github.com/vuejs/vue/issues/7649)
@@ -0,0 +1,242 @@
---
title: Scoped CSS Cannot Style Slot Content Directly
impact: HIGH
impactDescription: Slot content receives the parent component's scope, not the child's, causing styles to fail unexpectedly
type: gotcha
tags: [vue3, sfc, scoped-css, slots, deep-selector]
---
# Scoped CSS Cannot Style Slot Content Directly
**Impact: HIGH** - When a parent passes content through a slot, that content receives the parent component's scoped style attributes, not the child component's. This means the child component cannot style slot content with regular scoped CSS.
## Task Checklist
- [ ] Use `:deep()` selector in the wrapper component to style slot content
- [ ] Alternatively, use `:slotted()` pseudo-selector to target slotted elements
- [ ] For complex slot styling, consider using CSS modules or unscoped styles
- [ ] Document expected slot content structure when styling assumptions exist
**Problematic Code:**
```vue
<!-- Card.vue (child component) -->
<template>
<div class="card">
<div class="card-body">
<slot />
</div>
</div>
</template>
<style scoped>
.card-body {
padding: 1rem;
}
/* BAD: Won't apply to slot content! */
.card-body h2 {
color: #333;
margin-bottom: 0.5rem;
}
.card-body p {
color: #666;
}
</style>
```
```vue
<!-- Parent.vue -->
<template>
<Card>
<!-- This h2 and p won't be styled by Card's scoped CSS -->
<h2>Card Title</h2>
<p>Card description text.</p>
</Card>
</template>
```
**Correct Code:**
```vue
<!-- Card.vue - Using :slotted() -->
<template>
<div class="card">
<div class="card-body">
<slot />
</div>
</div>
</template>
<style scoped>
.card-body {
padding: 1rem;
}
/* GOOD: :slotted() targets slot content */
:slotted(h2) {
color: #333;
margin-bottom: 0.5rem;
}
:slotted(p) {
color: #666;
}
</style>
```
## Using :deep() Alternative
```vue
<!-- Card.vue - Using :deep() -->
<style scoped>
.card-body {
padding: 1rem;
}
/* :deep() also works for slot content */
.card-body :deep(h2) {
color: #333;
}
.card-body :deep(p) {
color: #666;
}
</style>
```
## Why This Happens
Slot content is compiled in the parent component's scope:
```vue
<!-- Parent template compiles to: -->
<Card>
<h2 data-v-parent123>Card Title</h2>
<p data-v-parent123>Card description</p>
</Card>
<!-- Card template compiles to: -->
<div class="card" data-v-card456>
<div class="card-body" data-v-card456>
<slot /> <!-- Content inserted WITHOUT data-v-card456 -->
</div>
</div>
```
The `<h2>` has `data-v-parent123`, but Card's scoped CSS expects `data-v-card456`.
## :slotted() vs :deep() for Slots
Both work, but have subtle differences:
```vue
<style scoped>
/* :slotted() - Specifically for slot content */
/* Only targets direct slotted elements */
:slotted(h2) {
color: blue;
}
/* :deep() - More general deep selector */
/* Can target nested elements within slot content */
.card-body :deep(h2) {
color: blue;
}
/* For nested elements in slot content, must use :deep() */
:slotted(.wrapper h2) { } /* Won't work for nested h2 */
.card-body :deep(.wrapper h2) { } /* Works for nested */
</style>
```
## Combining with Named Slots
```vue
<template>
<div class="card">
<header class="card-header">
<slot name="header" />
</header>
<div class="card-body">
<slot />
</div>
<footer class="card-footer">
<slot name="footer" />
</footer>
</div>
</template>
<style scoped>
/* Style specific slot content */
.card-header :slotted(h1),
.card-header :slotted(h2) {
margin: 0;
font-size: 1.25rem;
}
.card-body :slotted(p) {
margin-bottom: 1rem;
}
.card-footer :slotted(button) {
margin-right: 0.5rem;
}
</style>
```
## Performance Tip: Use Classes
Element selectors with `:slotted()` can be slower:
```vue
<style scoped>
/* SLOWER: Element selector */
:slotted(p) {
color: gray;
}
/* FASTER: Class selector */
:slotted(.card-text) {
color: gray;
}
</style>
```
## When to Use Unscoped Styles
For complex slot styling, unscoped styles may be cleaner:
```vue
<template>
<article class="article-card">
<slot />
</article>
</template>
<style>
/* Unscoped with unique prefix for complex content styling */
.article-card h1,
.article-card h2,
.article-card h3 {
font-family: Georgia, serif;
line-height: 1.2;
}
.article-card p {
line-height: 1.6;
}
.article-card img {
max-width: 100%;
}
.article-card blockquote {
border-left: 3px solid #ccc;
padding-left: 1rem;
}
</style>
```
## Reference
- [Vue.js Scoped CSS - Slotted Selectors](https://vuejs.org/api/sfc-css-features.html#slotted-selectors)
- [Vue.js Deep Selectors](https://vuejs.org/api/sfc-css-features.html#deep-selectors)
@@ -0,0 +1,195 @@
---
title: Variables in Script Setup Are Not Reactive by Default
impact: HIGH
impactDescription: Forgetting to wrap variables with ref() or reactive() causes silent reactivity failures in script setup
type: gotcha
tags: [vue3, sfc, script-setup, reactivity, ref, composition-api]
---
# Variables in Script Setup Are Not Reactive by Default
**Impact: HIGH** - Unlike Options API's `data()` which automatically makes properties reactive, variables declared in `<script setup>` are plain JavaScript values. You must explicitly use `ref()` or `reactive()` to make them reactive. Forgetting this causes the UI to not update when values change.
## Task Checklist
- [ ] Always wrap primitive values (strings, numbers, booleans) with `ref()`
- [ ] Use `reactive()` for objects when you don't need to reassign the whole object
- [ ] Remember to access `.value` on refs in script (not needed in templates)
- [ ] Use `computed()` from Vue, not a plain function, for derived reactive state
**Problematic Code:**
```vue
<script setup>
// BAD: These are NOT reactive!
let count = 0
let message = 'Hello'
let user = { name: 'John', age: 30 }
function increment() {
count++ // This change won't update the UI!
}
function updateMessage() {
message = 'World' // UI won't reflect this change!
}
</script>
<template>
<div>
<!-- Will always show initial values -->
<p>Count: {{ count }}</p>
<p>Message: {{ message }}</p>
<button @click="increment">Increment</button>
<button @click="updateMessage">Update</button>
</div>
</template>
```
**Correct Code:**
```vue
<script setup>
import { ref, reactive, computed } from 'vue'
// GOOD: Primitives wrapped with ref()
const count = ref(0)
const message = ref('Hello')
// GOOD: Object with reactive()
const user = reactive({ name: 'John', age: 30 })
// GOOD: Computed for derived state
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++ // Use .value for refs in script
}
function updateMessage() {
message.value = 'World'
}
function updateUser() {
user.name = 'Jane' // No .value needed for reactive objects
}
</script>
<template>
<div>
<!-- No .value needed in templates - Vue unwraps automatically -->
<p>Count: {{ count }}</p>
<p>Double: {{ doubleCount }}</p>
<p>Message: {{ message }}</p>
<p>User: {{ user.name }}</p>
<button @click="increment">Increment</button>
</div>
</template>
```
## Common Mistake: Plain Computed
```vue
<script setup>
import { ref } from 'vue'
const items = ref([1, 2, 3, 4, 5])
// BAD: Plain function, not reactive - won't update when items change
const total = items.value.reduce((sum, n) => sum + n, 0)
// BAD: Arrow function - recalculates but Vue doesn't track it
const getTotal = () => items.value.reduce((sum, n) => sum + n, 0)
</script>
<template>
<!-- total never updates, getTotal works but isn't optimal -->
<p>Total: {{ total }}</p>
</template>
```
```vue
<script setup>
import { ref, computed } from 'vue'
const items = ref([1, 2, 3, 4, 5])
// GOOD: computed() tracks dependencies and caches result
const total = computed(() => items.value.reduce((sum, n) => sum + n, 0))
</script>
<template>
<p>Total: {{ total }}</p> <!-- Updates when items change -->
</template>
```
## When to Use ref() vs reactive()
```vue
<script setup>
import { ref, reactive } from 'vue'
// Use ref() for:
// - Primitives (string, number, boolean)
// - Values you might reassign entirely
const count = ref(0)
const isLoading = ref(false)
const selectedId = ref<number | null>(null)
// Use reactive() for:
// - Objects/arrays you'll mutate but not reassign
// - When you want to avoid .value
const form = reactive({
name: '',
email: '',
errors: []
})
// Gotcha: Can't reassign reactive objects
const user = reactive({ name: 'John' })
// user = { name: 'Jane' } // This breaks reactivity!
// user.name = 'Jane' // This works
// Use ref() if you need to reassign objects
const userData = ref({ name: 'John' })
userData.value = { name: 'Jane' } // This works
</script>
```
## Template Automatic Unwrapping
Vue automatically unwraps refs in templates:
```vue
<script setup>
import { ref } from 'vue'
const count = ref(0)
const user = ref({ name: 'John' })
</script>
<template>
<!-- All of these work - no .value needed -->
<p>{{ count }}</p>
<p>{{ user.name }}</p>
<input v-model="count" type="number">
<button @click="count++">Increment</button>
</template>
```
But in event handlers written inline, you might still need `.value`:
```vue
<template>
<!-- This works (Vue handles it) -->
<button @click="count++">+1</button>
<!-- For complex logic, .value may be needed -->
<button @click="() => { count.value = Math.max(0, count.value - 1) }">
-1 (min 0)
</button>
</template>
```
## Reference
- [Vue.js Reactivity Fundamentals](https://vuejs.org/guide/essentials/reactivity-fundamentals.html)
- [Vue.js ref()](https://vuejs.org/api/reactivity-core.html#ref)
- [Vue.js reactive()](https://vuejs.org/api/reactivity-core.html#reactive)
@@ -0,0 +1,143 @@
---
title: Forward Slots to Child Components Correctly
impact: MEDIUM
impactDescription: Wrapper components that don't forward slots break slot functionality for consumers
type: best-practice
tags: [vue3, slots, component-composition, wrapper-components, slot-forwarding]
---
# Forward Slots to Child Components Correctly
**Impact: MEDIUM** - When creating wrapper components that enhance or extend other components, you need to forward slots from the parent to the wrapped child. Without proper slot forwarding, consumers of your wrapper cannot customize the inner component's slots.
## Task Checklist
- [ ] Use `v-for` with `$slots` to iterate over all provided slots
- [ ] Use dynamic slot names with `v-slot:[slotName]`
- [ ] Pass slot props through with `v-bind="slotProps"`
- [ ] Handle cases where slotProps might be undefined
**Basic Slot Forwarding Pattern:**
```vue
<!-- EnhancedButton.vue - Wrapper component -->
<script setup>
import BaseButton from './BaseButton.vue'
</script>
<template>
<div class="button-wrapper">
<BaseButton v-bind="$attrs">
<!-- Forward all slots to BaseButton -->
<template v-for="(_, slotName) in $slots" v-slot:[slotName]="slotProps">
<slot :name="slotName" v-bind="slotProps ?? {}" />
</template>
</BaseButton>
</div>
</template>
```
**Usage:**
```vue
<script setup>
import EnhancedButton from './EnhancedButton.vue'
</script>
<template>
<!-- Slots pass through to BaseButton -->
<EnhancedButton>
<template #icon>
<IconCheck />
</template>
<template #default>
Click me
</template>
</EnhancedButton>
</template>
```
## Handling Scoped Slots
When the child component provides slot props, you must forward them:
```vue
<!-- DataTableWrapper.vue -->
<script setup>
import DataTable from './DataTable.vue'
const props = defineProps(['data'])
</script>
<template>
<div class="table-container">
<DataTable :items="data">
<!-- Forward slots including scoped slot props -->
<template v-for="(_, slotName) in $slots" v-slot:[slotName]="slotProps">
<slot :name="slotName" v-bind="slotProps ?? {}" />
</template>
</DataTable>
</div>
</template>
```
```vue
<!-- Consumer can use scoped slot props -->
<DataTableWrapper :data="users">
<template #row="{ item, index }">
<tr>
<td>{{ index + 1 }}</td>
<td>{{ item.name }}</td>
</tr>
</template>
</DataTableWrapper>
```
## Alternative: Handling Undefined slotProps
Some scenarios require checking if slotProps exists:
```vue
<template>
<ChildComponent>
<template v-for="(_, name) in $slots" v-slot:[name]="slotProps">
<!-- Handle both scoped and non-scoped slots -->
<slot v-if="slotProps" :name="name" v-bind="slotProps" />
<slot v-else :name="name" />
</template>
</ChildComponent>
</template>
```
## Forwarding Specific Slots Only
If you only want to forward certain slots:
```vue
<template>
<ChildComponent>
<!-- Only forward header and footer slots -->
<template v-if="$slots.header" #header="slotProps">
<slot name="header" v-bind="slotProps ?? {}" />
</template>
<template v-if="$slots.footer" #footer="slotProps">
<slot name="footer" v-bind="slotProps ?? {}" />
</template>
<!-- Default slot handled differently -->
<slot />
</ChildComponent>
</template>
```
## Common Mistakes
| Mistake | Problem | Solution |
|---------|---------|----------|
| Not using `v-bind="slotProps"` | Scoped slot data lost | Always bind slotProps |
| Forgetting `?? {}` or null check | Error when slotProps undefined | Add nullish coalescing |
| Static slot names in loop | Only forwards one slot | Use `v-slot:[slotName]` dynamic syntax |
| Missing `v-for` key warning | Vue warning (non-critical) | Keys not needed for slot functions |
## Reference
- [Vue Land FAQ - Forwarding Slots](https://vue-land.github.io/faq/forwarding-slots)
- [Vue.js Slots - Scoped Slots](https://vuejs.org/guide/components/slots.html#scoped-slots)
@@ -0,0 +1,155 @@
---
title: Non-Template Content Is Implicitly Default Slot Content
impact: LOW
impactDescription: Unexpected content placement when mixing named slots with loose content
type: gotcha
tags: [vue3, slots, named-slots, default-slot, implicit-behavior]
---
# Non-Template Content Is Implicitly Default Slot Content
**Impact: LOW** - When using named slots, any top-level content not wrapped in a `<template>` tag is automatically treated as default slot content. This implicit behavior can cause confusion about where content will render.
## Task Checklist
- [ ] Understand that loose content goes to the default slot
- [ ] Use explicit `<template #default>` when clarity matters
- [ ] Keep slot content organization intentional
**The Implicit Behavior:**
```vue
<script setup>
import BaseLayout from './BaseLayout.vue'
</script>
<template>
<BaseLayout>
<template #header>
<h1>Page Title</h1>
</template>
<!-- These are IMPLICITLY in the default slot -->
<p>First paragraph of main content.</p>
<p>Second paragraph of main content.</p>
<template #footer>
<p>Footer content</p>
</template>
</BaseLayout>
</template>
```
The two `<p>` elements are automatically placed in `<slot>` (the default slot) in the child component.
**Equivalent Explicit Version:**
```vue
<template>
<BaseLayout>
<template #header>
<h1>Page Title</h1>
</template>
<!-- Explicit default slot -->
<template #default>
<p>First paragraph of main content.</p>
<p>Second paragraph of main content.</p>
</template>
<template #footer>
<p>Footer content</p>
</template>
</BaseLayout>
</template>
```
## When Implicit Behavior Causes Confusion
**Scattered Content:**
```vue
<template>
<BaseLayout>
<template #header>
<h1>Title</h1>
</template>
<p>Content A</p> <!-- Goes to default slot -->
<template #sidebar>
<nav>Navigation</nav>
</template>
<p>Content B</p> <!-- Also goes to default slot! -->
<template #footer>
<p>Footer</p>
</template>
<p>Content C</p> <!-- Also goes to default slot! -->
</BaseLayout>
</template>
```
All three `<p>` elements end up in the default slot together, which may not be the intended order or grouping.
**Clearer with Explicit Default:**
```vue
<template>
<BaseLayout>
<template #header>
<h1>Title</h1>
</template>
<template #default>
<p>Content A</p>
<p>Content B</p>
<p>Content C</p>
</template>
<template #sidebar>
<nav>Navigation</nav>
</template>
<template #footer>
<p>Footer</p>
</template>
</BaseLayout>
</template>
```
## Best Practices
| Scenario | Recommendation |
|----------|---------------|
| Only default slot used | Implicit is fine |
| Mixed named + default slots | Consider explicit `#default` |
| Complex layouts | Always use explicit templates |
| Team/shared codebase | Prefer explicit for clarity |
## The Child Component
```vue
<!-- BaseLayout.vue -->
<template>
<div class="layout">
<header>
<slot name="header"></slot>
</header>
<aside>
<slot name="sidebar"></slot>
</aside>
<main>
<!-- All implicit content ends up here -->
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
```
## Reference
- [Vue.js Slots - Named Slots](https://vuejs.org/guide/components/slots.html#named-slots)
@@ -0,0 +1,109 @@
---
title: Slot Name is Reserved and Not Included in Slot Props
impact: LOW
impactDescription: Expecting 'name' in scoped slot props when it's reserved causes confusion
type: gotcha
tags: [vue3, slots, scoped-slots, reserved-props, naming]
---
# Slot Name is Reserved and Not Included in Slot Props
**Impact: LOW** - When using scoped slots, the `name` attribute on the `<slot>` element is reserved for identifying the slot. It is not passed as part of the slot props to the parent component.
## Task Checklist
- [ ] Don't expect `name` in slot props - it's reserved
- [ ] Use a different prop name if you need to pass a name value
- [ ] Remember only explicitly bound attributes become slot props
**Incorrect Expectation:**
```vue
<!-- ChildComponent.vue -->
<template>
<div>
<slot name="header" title="Welcome"></slot>
</div>
</template>
```
```vue
<!-- ParentComponent.vue -->
<ChildComponent>
<template #header="props">
<!-- props = { title: "Welcome" } -->
<!-- 'name' is NOT included! -->
{{ props.name }} <!-- undefined -->
{{ props.title }} <!-- "Welcome" -->
</template>
</ChildComponent>
```
**If You Need to Pass a "Name" Value:**
```vue
<!-- ChildComponent.vue -->
<template>
<div>
<!-- Use a different prop name like 'slotName' or 'label' -->
<slot name="header" :label="slotLabel" :title="title"></slot>
</div>
</template>
<script setup>
const slotLabel = 'header'
const title = 'Welcome'
</script>
```
```vue
<!-- ParentComponent.vue -->
<ChildComponent>
<template #header="{ label, title }">
<h2>{{ title }}</h2>
<span>Section: {{ label }}</span>
</template>
</ChildComponent>
```
## What Gets Passed as Slot Props
| Attribute on `<slot>` | Passed to Parent? |
|----------------------|-------------------|
| `name` | No (reserved for slot identification) |
| `:text="message"` | Yes, as `text` |
| `:count="5"` | Yes, as `count` |
| `v-bind="object"` | Yes, spreads object properties |
| `class="..."` | No (not bound with `:`) |
## Multiple Named Slots Example
```vue
<!-- TabPanel.vue -->
<template>
<div class="tabs">
<slot name="tab1" :active="activeTab === 1" :label="'First Tab'"></slot>
<slot name="tab2" :active="activeTab === 2" :label="'Second Tab'"></slot>
</div>
</template>
<script setup>
import { ref } from 'vue'
const activeTab = ref(1)
</script>
```
```vue
<!-- Usage -->
<TabPanel>
<template #tab1="{ active, label }">
<!-- 'name' not available, but 'label' is -->
<button :class="{ active }">{{ label }}</button>
</template>
<template #tab2="{ active, label }">
<button :class="{ active }">{{ label }}</button>
</template>
</TabPanel>
```
## Reference
- [Vue.js Slots - Scoped Slots](https://vuejs.org/guide/components/slots.html#scoped-slots)
@@ -0,0 +1,95 @@
---
title: Use Explicit Default Template When Mixing Named and Scoped Slots
impact: HIGH
impactDescription: Mixing v-slot on component with named slots inside causes ambiguous scope and compilation errors
type: gotcha
tags: [vue3, slots, scoped-slots, named-slots, compilation-error]
---
# Use Explicit Default Template When Mixing Named and Scoped Slots
**Impact: HIGH** - When a component uses both the default scoped slot and named slots, you must use an explicit `<template #default>` for the default slot. Using `v-slot` directly on the component while having nested named slot templates causes scope ambiguity and compilation errors.
## Task Checklist
- [ ] When using named slots alongside a default slot with props, always use explicit `<template #default>`
- [ ] Never mix `v-slot` on the component element with `<template #name>` inside
- [ ] Keep slot scope clear and unambiguous
**Incorrect:**
```vue
<script setup>
import MyComponent from './MyComponent.vue'
</script>
<template>
<!-- BAD: v-slot on component + named template inside causes ambiguity -->
<MyComponent v-slot="{ message }">
<p>{{ message }}</p>
<template #footer>
<!-- Ambiguous: Is 'message' available here? Vue can't determine -->
<p>Footer: {{ message }}</p>
</template>
</MyComponent>
</template>
```
This causes a compilation error because Vue cannot determine:
1. Whether `message` from the default slot should be available in the footer slot
2. Which scope applies to the non-template content
**Correct:**
```vue
<script setup>
import MyComponent from './MyComponent.vue'
</script>
<template>
<!-- GOOD: Explicit template for each slot with clear scope -->
<MyComponent>
<template #default="{ message }">
<p>{{ message }}</p>
</template>
<template #footer>
<!-- Clear: footer slot has its own scope, no access to default's 'message' -->
<p>Footer content here</p>
</template>
</MyComponent>
</template>
```
**Correct - When Footer Also Has Props:**
```vue
<script setup>
import MyComponent from './MyComponent.vue'
</script>
<template>
<MyComponent>
<template #default="{ message }">
<p>{{ message }}</p>
</template>
<template #footer="{ year }">
<!-- Each slot receives its own props -->
<p>Copyright {{ year }}</p>
</template>
</MyComponent>
</template>
```
## The Rule
When you have **any** named slots (`<template #name>`), always use explicit templates for **all** slots, including the default slot. This makes scope boundaries clear and prevents compilation errors.
| Pattern | Valid? | Notes |
|---------|--------|-------|
| `v-slot` on component only | Yes | Single default scoped slot |
| Named templates only | Yes | Multiple named slots |
| `v-slot` on component + named templates | No | Ambiguous scope |
| All explicit templates | Yes | Clear scope for each slot |
## Reference
- [Vue.js Slots - Named Scoped Slots](https://vuejs.org/guide/components/slots.html#named-scoped-slots)
@@ -0,0 +1,135 @@
---
title: Slot Content Only Has Access to Parent Component Scope
impact: HIGH
impactDescription: Attempting to access child component data in slot content results in undefined values or errors
type: gotcha
tags: [vue3, slots, scope, reactivity, common-mistake]
---
# Slot Content Only Has Access to Parent Component Scope
**Impact: HIGH** - Slot content is compiled in the parent component's scope and cannot access data defined in the child component. This follows JavaScript's lexical scoping rules and is a common source of confusion.
When you provide content for a slot, that content is defined in your parent template and can only access data available in the parent component. The child component's internal state is not accessible unless explicitly passed via scoped slots.
## Task Checklist
- [ ] Remember that slot content is compiled in parent scope
- [ ] Never try to access child component data directly in slot content
- [ ] Use scoped slots when child data needs to be exposed to parent
- [ ] Check that all template expressions reference data available in the current component
**Incorrect:**
```vue
<!-- Parent.vue -->
<script setup>
import SubmitButton from './SubmitButton.vue'
</script>
<template>
<!-- BAD: Trying to access child's buttonText - this will be undefined -->
<SubmitButton>{{ buttonText }}</SubmitButton>
<!-- BAD: Trying to access child's isLoading state -->
<SubmitButton>
<span v-if="isLoading">Loading...</span>
<span v-else>Submit</span>
</SubmitButton>
</template>
```
```vue
<!-- SubmitButton.vue (Child) -->
<script setup>
import { ref } from 'vue'
const buttonText = ref('Click me') // Not accessible in parent's slot content
const isLoading = ref(false) // Not accessible in parent's slot content
</script>
<template>
<button>
<slot></slot>
</button>
</template>
```
**Correct - Use Scoped Slots:**
```vue
<!-- SubmitButton.vue (Child) - Expose data via slot props -->
<script setup>
import { ref } from 'vue'
const buttonText = ref('Click me')
const isLoading = ref(false)
</script>
<template>
<button>
<!-- Pass child data as slot props -->
<slot :text="buttonText" :loading="isLoading"></slot>
</button>
</template>
```
```vue
<!-- Parent.vue -->
<script setup>
import SubmitButton from './SubmitButton.vue'
</script>
<template>
<!-- GOOD: Receive child data via scoped slot -->
<SubmitButton v-slot="{ text, loading }">
<span v-if="loading">Loading...</span>
<span v-else>{{ text }}</span>
</SubmitButton>
</template>
```
**Correct - Use Parent Data:**
```vue
<!-- Parent.vue -->
<script setup>
import { ref } from 'vue'
import SubmitButton from './SubmitButton.vue'
// Define data in parent where slot content is compiled
const message = ref('Submit Form')
const isSubmitting = ref(false)
</script>
<template>
<!-- GOOD: Using parent's own data in slot content -->
<SubmitButton>
<span v-if="isSubmitting">Processing...</span>
<span v-else>{{ message }}</span>
</SubmitButton>
</template>
```
## The Function Analogy
Think of slots as function parameters:
```javascript
// Slot content is like a callback defined in parent scope
function Parent() {
const parentData = 'Hello'
// This callback can only see parentData, not childData
Child((slotProps) => {
return parentData + (slotProps?.text || '')
})
}
function Child(slotCallback) {
const childData = 'World' // Not visible to callback
// Must explicitly pass data via slot props
return slotCallback({ text: childData })
}
```
## Reference
- [Vue.js Slots - Render Scope](https://vuejs.org/guide/components/slots.html#render-scope)
@@ -0,0 +1,122 @@
---
title: v-slot Can Only Be Used on Components or Template Tags
impact: HIGH
impactDescription: Using v-slot on HTML elements causes compilation errors
type: gotcha
tags: [vue3, slots, v-slot, compilation-error, common-mistake]
---
# v-slot Can Only Be Used on Components or Template Tags
**Impact: HIGH** - The `v-slot` directive (and its shorthand `#`) can only be used on Vue components or `<template>` tags. Using it on native HTML elements like `<div>` or `<span>` causes a Vue compilation error.
## Task Checklist
- [ ] Only use `v-slot` on component elements or `<template>` tags
- [ ] When using default scoped slot shorthand, apply to the component itself
- [ ] For named slots, always use `<template #name>` syntax
**Incorrect:**
```vue
<template>
<!-- BAD: v-slot on a native HTML element -->
<div v-slot:header>
<h1>Title</h1>
</div>
<!-- BAD: Shorthand on HTML element -->
<span #default="{ item }">
{{ item.name }}
</span>
<!-- BAD: v-slot inside a plain HTML element -->
<div>
<p v-slot:content>Some text</p>
</div>
</template>
```
These cause the error: `v-slot can only be used on components or <template> tags`
**Correct:**
```vue
<template>
<!-- GOOD: v-slot on component element (default scoped slot) -->
<MyComponent v-slot="{ item }">
{{ item.name }}
</MyComponent>
<!-- GOOD: Named slots use template tags -->
<BaseLayout>
<template #header>
<h1>Title</h1>
</template>
<template #default>
<p>Main content</p>
</template>
<template #footer>
<p>Footer content</p>
</template>
</BaseLayout>
<!-- GOOD: Shorthand on component for default slot -->
<FancyList #default="{ item }">
<div>{{ item.name }}</div>
</FancyList>
</template>
```
## Common Scenarios
### Wrapping Slot Content in HTML
If you need HTML wrappers around slot content, put them inside the template:
```vue
<!-- WRONG -->
<MyComponent>
<div v-slot:header class="header-wrapper">
<h1>Title</h1>
</div>
</MyComponent>
<!-- CORRECT -->
<MyComponent>
<template #header>
<div class="header-wrapper">
<h1>Title</h1>
</div>
</template>
</MyComponent>
```
### Multiple v-slot on Same Element
Another error occurs when you have multiple v-slot directives - only the first is recognized:
```vue
<!-- BAD: Multiple v-slot directives -->
<MyComponent v-slot:header v-slot:footer>
Content
</MyComponent>
<!-- GOOD: Separate template for each slot -->
<MyComponent>
<template #header>Header</template>
<template #footer>Footer</template>
</MyComponent>
```
## Valid v-slot Locations
| Element Type | v-slot Allowed? | Example |
|--------------|-----------------|---------|
| Component | Yes | `<MyComponent v-slot="props">` |
| `<template>` | Yes | `<template #header>` |
| `<div>` | No | Compilation error |
| `<span>` | No | Compilation error |
| Any HTML element | No | Compilation error |
## Reference
- [Vue.js Slots](https://vuejs.org/guide/components/slots.html)
- [DeepScan - vue-misused-v-slot](https://deepscan.io/docs/rules/vue-misused-v-slot)
@@ -0,0 +1,280 @@
---
title: Understand and Fix SSR Hydration Mismatches
impact: HIGH
impactDescription: Hydration mismatches cause visual flickering, performance loss, and broken functionality
type: gotcha
tags: [vue3, ssr, hydration, debugging, nuxt, server-side-rendering]
---
# Understand and Fix SSR Hydration Mismatches
**Impact: HIGH** - Hydration mismatches occur when the HTML rendered on the client differs from what the server rendered. Vue attempts to recover by discarding and re-rendering mismatched nodes, causing performance degradation, visual flickering, and potentially broken event handlers.
Understanding the common causes helps you prevent and debug these issues effectively.
## Task Checklist
- [ ] Validate HTML structure for proper nesting (no div in p, no nested a tags)
- [ ] Move random value generation to onMounted or use seeded randoms
- [ ] Format dates/times on client side only
- [ ] Use `data-allow-mismatch` (Vue 3.5+) for intentional mismatches
- [ ] Check for browser-modified HTML in dev tools
## Cause 1: Invalid HTML Nesting
Browsers auto-correct invalid HTML, creating different DOM than Vue expects.
**Incorrect:**
```vue
<template>
<!-- WRONG: <div> cannot be inside <p> -->
<p>
<div>This will break hydration</div>
</p>
<!-- WRONG: <a> cannot be inside <a> -->
<a href="/parent">
<a href="/child">Nested link</a>
</a>
<!-- WRONG: Block elements in inline elements -->
<span>
<div>Block in inline</div>
</span>
</template>
```
Browser converts the first example to:
```html
<p></p>
<div>This will break hydration</div>
<p></p>
```
**Correct:**
```vue
<template>
<!-- CORRECT: Use appropriate nesting -->
<div>
<div>This works fine</div>
</div>
<!-- CORRECT: Single link with event handling -->
<a href="/parent" @click="handleParentClick">
<span @click.stop="handleChildClick">Nested action</span>
</a>
<!-- CORRECT: Block element wrapper -->
<div>
<div>Block in block</div>
</div>
</template>
```
## Cause 2: Random Values in Render
Server and client generate different random values.
**Incorrect:**
```vue
<template>
<!-- WRONG: Different ID on server vs client -->
<div :id="'field-' + Math.random()">
Form field
</div>
<!-- WRONG: Random order differs -->
<div v-for="item in shuffledItems" :key="item.id">
{{ item.name }}
</div>
</template>
<script setup>
import { computed } from 'vue'
const items = [/* ... */]
// WRONG: Random shuffle runs differently on server and client
const shuffledItems = computed(() =>
[...items].sort(() => Math.random() - 0.5)
)
</script>
```
**Correct - Client-Only Random:**
```vue
<template>
<div :id="fieldId">
Form field
</div>
<div v-for="item in displayItems" :key="item.id">
{{ item.name }}
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const items = [/* ... */]
// CORRECT: Start with deterministic value
const fieldId = ref('field-default')
const displayItems = ref(items) // Original order on server
onMounted(() => {
// Randomize only on client
fieldId.value = 'field-' + Math.random().toString(36).slice(2)
displayItems.value = [...items].sort(() => Math.random() - 0.5)
})
</script>
```
**Correct - Seeded Random:**
```javascript
// utils/seededRandom.js
export function createSeededRandom(seed) {
return function() {
seed = (seed * 9301 + 49297) % 233280
return seed / 233280
}
}
// Use same seed on server and client
const seed = 12345 // Could be based on user ID, page, etc.
const random = createSeededRandom(seed)
```
## Cause 3: Timezone and Date Differences
Server may be in different timezone than client.
**Incorrect:**
```vue
<template>
<!-- WRONG: Server time != client time -->
<span>{{ new Date().toLocaleTimeString() }}</span>
<!-- WRONG: Server formats dates in server's timezone -->
<span>{{ formatDate(article.createdAt) }}</span>
</template>
<script setup>
function formatDate(date) {
return new Date(date).toLocaleDateString()
}
</script>
```
**Correct:**
```vue
<template>
<!-- CORRECT: Render placeholder, update on client -->
<span>{{ displayTime || 'Loading...' }}</span>
<!-- CORRECT: Use UTC or defer to client -->
<span>{{ formattedDate }}</span>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
const props = defineProps(['article'])
const displayTime = ref(null)
const isClient = ref(false)
onMounted(() => {
displayTime.value = new Date().toLocaleTimeString()
isClient.value = true
})
// CORRECT: Server renders UTC, client converts to local
const formattedDate = computed(() => {
if (!props.article?.createdAt) return ''
if (isClient.value) {
// Client: user's local timezone
return new Date(props.article.createdAt).toLocaleDateString()
} else {
// Server: consistent UTC format
return new Date(props.article.createdAt).toISOString().split('T')[0]
}
})
</script>
```
## Cause 4: Browser Extensions and Modifications
Browser extensions can inject content into the DOM.
**Mitigation:**
```vue
<template>
<!-- Use data-allow-mismatch for areas extensions might modify -->
<head data-allow-mismatch>
<title>{{ pageTitle }}</title>
</head>
</template>
```
## Vue 3.5+ Suppressing Intentional Mismatches
```vue
<template>
<!-- Suppress specific mismatch types -->
<div data-allow-mismatch="text">
{{ clientOnlyText }}
</div>
<!-- Suppress all mismatches for this element -->
<div data-allow-mismatch>
<ComplexClientComponent />
</div>
</template>
```
Valid `data-allow-mismatch` values:
- `text` - Text content mismatches
- `children` - Child element mismatches
- `class` - Class attribute mismatches
- `style` - Style attribute mismatches
- `attribute` - Other attribute mismatches
- (no value) - All mismatches
## Debugging Hydration Mismatches
```javascript
// Enable detailed hydration mismatch warnings in development
// vite.config.js
export default {
define: {
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true
}
}
```
```vue
<script setup>
import { onMounted } from 'vue'
// Debug: Compare server HTML with client expectation
onMounted(() => {
const serverHTML = document.getElementById('app').innerHTML
console.log('Server rendered:', serverHTML)
})
</script>
```
## Common Error Messages
| Error | Likely Cause |
|-------|--------------|
| "Hydration text content mismatch" | Different text on server/client (dates, random) |
| "Hydration children mismatch" | Invalid HTML nesting, conditional rendering |
| "Hydration attribute mismatch" | Dynamic attributes with different values |
| "Hydration node mismatch" | Completely different elements rendered |
## Reference
- [Vue.js SSR Guide - Hydration Mismatch](https://vuejs.org/guide/scaling-up/ssr.html#hydration-mismatch)
- [Nuxt Hydration Best Practices](https://nuxt.com/docs/guide/best-practices/hydration)
- [data-allow-mismatch RFC](https://github.com/vuejs/core/pull/9562)
@@ -0,0 +1,256 @@
---
title: Guard Platform-Specific APIs in Universal SSR Code
impact: HIGH
impactDescription: Accessing browser-only APIs on server causes crashes; Node.js APIs fail in browser
type: gotcha
tags: [vue3, ssr, browser-api, nodejs, universal, isomorphic, server-side-rendering]
---
# Guard Platform-Specific APIs in Universal SSR Code
**Impact: HIGH** - SSR applications run the same code on both server (Node.js) and client (browser). Browser APIs like `window`, `document`, and `localStorage` don't exist in Node.js and will throw `ReferenceError`. Similarly, Node.js APIs like `fs` and `process` aren't available in browsers.
Universal/isomorphic code must guard platform-specific API access or use libraries that work on both platforms.
## Task Checklist
- [ ] Never access `window`, `document`, `navigator` in `setup()` or `created()`
- [ ] Move browser API access to `onMounted()` lifecycle hook
- [ ] Use `typeof window !== 'undefined'` guard when needed outside lifecycle
- [ ] Use cross-platform libraries for common functionality (fetch, storage)
- [ ] Use Nuxt's `process.client` / `process.server` guards in Nuxt projects
## Common Browser APIs That Break SSR
| API | Node.js Behavior |
|-----|-----------------|
| `window` | `ReferenceError: window is not defined` |
| `document` | `ReferenceError: document is not defined` |
| `localStorage` / `sessionStorage` | `ReferenceError` |
| `navigator` | `ReferenceError` |
| `location` | `ReferenceError` |
| `history` | `ReferenceError` |
| `alert` / `confirm` / `prompt` | `ReferenceError` |
| `requestAnimationFrame` | `ReferenceError` |
| `IntersectionObserver` | `ReferenceError` |
| `ResizeObserver` | `ReferenceError` |
**Incorrect - Crashes on Server:**
```javascript
// WRONG: These run during setup/SSR - crashes in Node.js
const width = ref(window.innerWidth)
const theme = localStorage.getItem('theme')
const userAgent = navigator.userAgent
```
```vue
<script setup>
import { ref } from 'vue'
// WRONG: Runs on server, crashes
const scrollY = ref(window.scrollY)
// WRONG: document doesn't exist on server
document.title = 'My Page'
</script>
```
**Correct - Use onMounted:**
```vue
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// Safe defaults that work on server
const width = ref(0)
const theme = ref('light')
const scrollY = ref(0)
onMounted(() => {
// Browser APIs only accessed after mount (client-only)
width.value = window.innerWidth
theme.value = localStorage.getItem('theme') || 'light'
scrollY.value = window.scrollY
// Event listeners safe in mounted
window.addEventListener('resize', handleResize)
window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
window.removeEventListener('scroll', handleScroll)
})
function handleResize() {
width.value = window.innerWidth
}
function handleScroll() {
scrollY.value = window.scrollY
}
</script>
```
**Correct - Guard with typeof:**
```javascript
// When you need to check outside lifecycle hooks
function getStoredValue(key, defaultValue) {
if (typeof window !== 'undefined' && window.localStorage) {
return localStorage.getItem(key) ?? defaultValue
}
return defaultValue
}
// Composable with SSR awareness
export function useMediaQuery(query) {
const matches = ref(false)
// Only run on client
if (typeof window !== 'undefined') {
const mediaQuery = window.matchMedia(query)
matches.value = mediaQuery.matches
// Setup listener in lifecycle
onMounted(() => {
const handler = (e) => { matches.value = e.matches }
mediaQuery.addEventListener('change', handler)
onUnmounted(() => mediaQuery.removeEventListener('change', handler))
})
}
return matches
}
```
## Nuxt.js Guards
```vue
<script setup>
// Nuxt provides process.client and process.server
if (process.client) {
// Only runs in browser
window.analytics.track('page_view')
}
if (process.server) {
// Only runs on server
console.log('Rendering on server')
}
</script>
```
```vue
<template>
<!-- ClientOnly component for client-only rendering -->
<ClientOnly>
<BrowserOnlyChart :data="chartData" />
<template #fallback>
<ChartSkeleton />
</template>
</ClientOnly>
</template>
```
## Cross-Platform Libraries
Use libraries that abstract platform differences:
```javascript
// Fetch - works in both Node.js 18+ and browsers
const response = await fetch('/api/data')
// For older Node.js, use node-fetch or axios
import axios from 'axios'
const { data } = await axios.get('/api/data')
```
```javascript
// Universal cookie handling
import Cookies from 'js-cookie' // Client only
import { parse } from 'cookie' // Works both
// In Nuxt, use useCookie()
const token = useCookie('auth-token')
```
## Common Node.js APIs That Break in Browser
| API | Browser Behavior |
|-----|-----------------|
| `fs` | Module not found |
| `path` | Module not found |
| `process` (full) | Undefined or limited |
| `Buffer` | Undefined (unless polyfilled) |
| `__dirname` / `__filename` | Undefined |
| `require()` | Undefined in ES modules |
**Incorrect:**
```javascript
// WRONG: Node.js APIs in universal code
import fs from 'fs'
const config = JSON.parse(fs.readFileSync('./config.json'))
```
**Correct - Separate Server Code:**
```javascript
// server/utils.js - Server-only file
import fs from 'fs'
export function loadConfig() {
return JSON.parse(fs.readFileSync('./config.json'))
}
// app.js - Universal code uses API instead
const config = await fetch('/api/config').then(r => r.json())
```
## Environment Detection Utility
```javascript
// utils/environment.js
export const isClient = typeof window !== 'undefined'
export const isServer = !isClient
export const isBrowser = isClient && typeof document !== 'undefined'
export const isNode = typeof process !== 'undefined' &&
process.versions?.node != null
// Usage
import { isClient, isServer } from '@/utils/environment'
if (isClient) {
// Browser-specific code
}
```
## Third-Party Library Issues
Some libraries auto-access browser APIs on import:
```javascript
// WRONG: Library accesses window on import
import SomeChartLibrary from 'some-chart-library'
// ^ Crashes on server if library does: const x = window.something
```
**Correct - Dynamic Import:**
```vue
<script setup>
import { defineAsyncComponent } from 'vue'
// Dynamic import only loads on client
const Chart = defineAsyncComponent(() =>
import('some-chart-library').then(m => m.ChartComponent)
)
</script>
<template>
<ClientOnly>
<Chart :data="data" />
</ClientOnly>
</template>
```
## Reference
- [Vue.js SSR - Platform-Specific APIs](https://vuejs.org/guide/scaling-up/ssr.html#access-to-platform-specific-apis)
- [Nuxt ClientOnly Component](https://nuxt.com/docs/api/components/client-only)
- [MDN: Web APIs](https://developer.mozilla.org/en-US/docs/Web/API)
@@ -0,0 +1,276 @@
---
title: Prevent Cross-Request State Pollution in SSR Applications
impact: CRITICAL
impactDescription: Singleton stores in SSR share state across all server requests, potentially leaking user data between requests
type: gotcha
tags: [vue3, ssr, state-management, pinia, vuex, security, server-side-rendering, nuxt]
---
# Prevent Cross-Request State Pollution in SSR Applications
**Impact: CRITICAL** - In Server-Side Rendering (SSR) applications, a singleton store pattern creates a single instance that is shared across all server requests. This means data from one user's request could leak into another user's response, causing serious security and data integrity issues.
This is one of the most critical gotchas in Vue state management that can have severe production consequences.
## Task Checklist
- [ ] Never use a singleton store pattern in SSR applications
- [ ] Create a fresh store instance per request when using SSR
- [ ] Use Pinia which handles SSR state management correctly
- [ ] Test SSR state isolation with concurrent requests
- [ ] Review any global reactive state for SSR compatibility
## The Problem: Singleton State in SSR
```javascript
// store.js - DANGEROUS for SSR
import { reactive } from 'vue'
// This is a singleton - same instance for ALL requests
export const store = reactive({
user: null,
cart: [],
preferences: {}
})
```
**What happens in SSR:**
1. Request A comes in for User A
2. Server sets `store.user = userA`
3. Before response completes, Request B arrives for User B
4. Request B sees `store.user = userA` (User A's data leaked!)
5. Server sets `store.user = userB`
6. Request A's response might now contain User B's data
This creates unpredictable behavior and potential security vulnerabilities.
## Solution 1: Use Pinia (Recommended)
Pinia handles SSR correctly by creating fresh store instances per request:
```javascript
// stores/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
user: null,
preferences: {}
}),
actions: {
setUser(user) {
this.user = user
}
}
})
```
```javascript
// main.js (or entry-server.js)
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
// For SSR: Create fresh instances per request
export function createAppInstance() {
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
return { app, pinia }
}
```
```javascript
// entry-server.js
import { createAppInstance } from './main'
import { renderToString } from 'vue/server-renderer'
export async function render(url, context) {
// Fresh app and store instance per request
const { app, pinia } = createAppInstance()
// ... setup router, fetch data, etc.
const html = await renderToString(app)
// Serialize state for client hydration
const state = pinia.state.value
return { html, state }
}
```
```javascript
// entry-client.js - Hydrate from serialized state
import { createAppInstance } from './main'
const { app, pinia } = createAppInstance()
// Restore server state before mounting
if (window.__PINIA_STATE__) {
pinia.state.value = window.__PINIA_STATE__
}
app.mount('#app')
```
## Solution 2: Factory Pattern for Hand-Rolled State
If not using Pinia, create a factory function:
```javascript
// store.js - SSR-safe with factory
import { reactive, readonly } from 'vue'
// Factory function creates fresh state per call
export function createStore() {
const state = reactive({
user: null,
cart: [],
preferences: {}
})
return {
state: readonly(state),
setUser(user) {
state.user = user
},
addToCart(item) {
state.cart.push(item)
}
}
}
```
```javascript
// entry-server.js
import { createStore } from './store'
import { provide } from 'vue'
export async function render(url) {
const app = createApp(App)
// Fresh store instance for this request only
const store = createStore()
app.provide('store', store)
// ... render
}
```
## Solution 3: Context-Based State (Advanced)
For frameworks like Nuxt, use request context:
```javascript
// composables/useRequestState.js
import { useSSRContext } from 'vue'
export function useRequestState(key, initialValue) {
if (import.meta.env.SSR) {
const ctx = useSSRContext()
ctx.state = ctx.state || {}
if (!(key in ctx.state)) {
ctx.state[key] = initialValue()
}
return ctx.state[key]
}
// Client-side: use regular reactive state
return reactive(initialValue())
}
```
## Nuxt.js Handles This Automatically
In Nuxt 3, state isolation is handled automatically:
```javascript
// Nuxt automatically creates fresh Pinia instance per request
// You can use stores normally
export default defineNuxtPlugin(async (nuxtApp) => {
const userStore = useUserStore()
await userStore.fetchUser()
})
```
## Testing for State Pollution
```javascript
// test/ssr-state-isolation.test.js
import { describe, it, expect } from 'vitest'
import { render } from './entry-server'
describe('SSR State Isolation', () => {
it('should not leak state between concurrent requests', async () => {
// Simulate concurrent requests
const [result1, result2] = await Promise.all([
render('/user/1', { userId: '1' }),
render('/user/2', { userId: '2' })
])
// Each should have their own user data
expect(result1.html).toContain('User 1')
expect(result2.html).toContain('User 2')
// State should not be mixed
expect(result1.html).not.toContain('User 2')
expect(result2.html).not.toContain('User 1')
})
})
```
```javascript
// Alternative: Test store isolation directly
import { createApp } from './app.js'
test('requests do not share state', async () => {
// Simulate two concurrent requests
const { app: app1, store: store1 } = createApp()
const { app: app2, store: store2 } = createApp()
store1.user = { id: 1, name: 'Alice' }
store2.user = { id: 2, name: 'Bob' }
// Each should have its own state
expect(store1.user.name).toBe('Alice')
expect(store2.user.name).toBe('Bob')
})
```
## Red Flags to Watch For
```javascript
// ANY module-level reactive state is dangerous in SSR
// BAD: Module-level reactive
export const globalUser = ref(null)
// BAD: Module-level reactive object
export const appState = reactive({})
// BAD: Shared Map/Set
export const cache = new Map()
// BAD: Even plain objects can be problematic
let requestCount = 0 // Shared across requests
```
## Why Pinia is Recommended for SSR
1. **Automatic request isolation** - Fresh store instances per request
2. **Built-in state serialization** - Easy hydration on client
3. **DevTools support** - Debug state on both server and client
4. **TypeScript support** - Type-safe state management
5. **Tested patterns** - Battle-tested SSR handling
## Reference
- [Vue.js State Management - SSR Considerations](https://vuejs.org/guide/scaling-up/state-management.html#ssr-considerations)
- [Pinia SSR Guide](https://pinia.vuejs.org/ssr/)
- [Vue SSR Guide](https://vuejs.org/guide/scaling-up/ssr.html)
@@ -0,0 +1,127 @@
# Suspense Has No Built-in Error Handling
## Rule
`<Suspense>` does not provide error handling via the component itself. You must implement error handling using `errorCaptured` option or `onErrorCaptured()` hook in a parent component to catch async errors.
## Why This Matters
Without explicit error handling, async errors in suspended components will propagate uncaught, potentially crashing the application or leaving users stuck on loading states. Unlike React's Error Boundaries, Vue's Suspense requires manual error boundary implementation.
## Bad Code
```vue
<script setup>
// No error handling - async errors will propagate uncaught
</script>
<template>
<Suspense>
<AsyncComponent />
<template #fallback>
Loading...
</template>
</Suspense>
</template>
```
## Good Code
```vue
<script setup>
import { ref, onErrorCaptured } from 'vue'
import AsyncComponent from './AsyncComponent.vue'
const error = ref(null)
onErrorCaptured((err) => {
error.value = err
return false // Prevent error from propagating further
})
</script>
<template>
<div v-if="error" class="error-state">
<p>Something went wrong: {{ error.message }}</p>
<button @click="error = null">Retry</button>
</div>
<Suspense v-else>
<AsyncComponent />
<template #fallback>
Loading...
</template>
</Suspense>
</template>
```
## Reusable Error Boundary Pattern
```vue
<!-- ErrorBoundary.vue -->
<script setup>
import { ref, onErrorCaptured } from 'vue'
const props = defineProps({
fallback: {
type: String,
default: 'Something went wrong'
}
})
const emit = defineEmits(['error'])
const error = ref(null)
onErrorCaptured((err, instance, info) => {
error.value = { err, instance, info }
emit('error', { err, instance, info })
return false
})
const reset = () => {
error.value = null
}
defineExpose({ reset })
</script>
<template>
<slot v-if="!error" />
<slot v-else name="error" :error="error" :reset="reset">
<div class="error-boundary">
{{ fallback }}
<button @click="reset">Retry</button>
</div>
</slot>
</template>
```
```vue
<!-- Usage -->
<template>
<ErrorBoundary @error="logError">
<Suspense>
<AsyncDashboard />
<template #fallback>Loading dashboard...</template>
</Suspense>
<template #error="{ error, reset }">
<DashboardError :error="error" @retry="reset" />
</template>
</ErrorBoundary>
</template>
```
## Key Points
1. Always wrap `<Suspense>` with error handling logic in production
2. Use `onErrorCaptured` for Composition API or `errorCaptured` option for Options API
3. Return `false` from the error handler to stop propagation
4. Consider creating a reusable `ErrorBoundary` component to reduce boilerplate
5. Provide a way for users to retry failed operations
## References
- [Vue.js Suspense Documentation](https://vuejs.org/guide/built-ins/suspense#error-handling)
- [Vue.js onErrorCaptured](https://vuejs.org/api/composition-api-lifecycle#onerrorcaptured)
@@ -0,0 +1,159 @@
# Suspense SSR Hydration Issues and Workarounds
## Rule
`<Suspense>` has known issues with SSR hydration, particularly with async components. During initial hydration, Suspense may not properly include child components within its "cloak of suspense," leading to hydration mismatches, flickering, or runtime crashes.
## Why This Matters
In SSR applications, hydration mismatches cause:
- Visual flickering as the client re-renders
- Loss of state in affected components
- Console warnings in development (silent failures in production)
- Potential runtime crashes in edge cases
- Poor user experience, especially on slower networks
## Bad Code
```vue
<template>
<!-- Async component directly in Suspense can fail hydration -->
<Suspense>
<AsyncDashboard />
<template #fallback>
Loading...
</template>
</Suspense>
</template>
<script setup>
import { defineAsyncComponent } from 'vue'
const AsyncDashboard = defineAsyncComponent(
() => import('./Dashboard.vue')
)
</script>
```
## Good Code
### Solution 1: Wrap Async Components with Suspense
```vue
<template>
<!-- Each async component wrapped in its own Suspense -->
<div class="dashboard">
<Suspense>
<AsyncHeader />
<template #fallback><HeaderSkeleton /></template>
</Suspense>
<Suspense>
<AsyncContent />
<template #fallback><ContentSkeleton /></template>
</Suspense>
</div>
</template>
```
### Solution 2: Use ClientOnly Wrapper (Nuxt/SSR Frameworks)
```vue
<template>
<!-- Prevent SSR for problematic async components -->
<ClientOnly>
<Suspense>
<AsyncDashboard />
<template #fallback>
Loading dashboard...
</template>
</Suspense>
<template #fallback>
<DashboardSkeleton />
</template>
</ClientOnly>
</template>
```
### Solution 3: Prefetch with Proper Stale Time (with TanStack Query)
```vue
<script setup>
import { useQuery, useQueryClient } from '@tanstack/vue-query'
// IMPORTANT: All useQuery calls must be BEFORE any await
const { data, suspense } = useQuery({
queryKey: ['dashboard'],
queryFn: fetchDashboardData,
staleTime: 1000 * 60 * 5, // 5 minutes - prevents refetch after hydration
})
// Wait for suspense AFTER all useQuery calls
await suspense()
// Now safe to use data
</script>
```
### Solution 4: Handle Hydration Errors Gracefully
```vue
<script setup>
import { ref, onErrorCaptured, onMounted } from 'vue'
const hydrationError = ref(false)
const isClient = ref(false)
onMounted(() => {
isClient.value = true
})
onErrorCaptured((err) => {
if (err.message?.includes('hydration')) {
hydrationError.value = true
return false
}
})
</script>
<template>
<div v-if="hydrationError" class="hydration-recovery">
<!-- Force client-only re-render -->
<Suspense v-if="isClient">
<AsyncContent />
<template #fallback>Recovering...</template>
</Suspense>
</div>
<Suspense v-else>
<AsyncContent />
<template #fallback>Loading...</template>
</Suspense>
</template>
```
## Common SSR + Suspense Issues
| Issue | Cause | Solution |
|-------|-------|----------|
| Hydration mismatch | Async chunk not loaded in time | Wrap with Suspense or use ClientOnly |
| Empty flash on Safari | Slow chunk loading | Preload critical chunks, use skeleton |
| useQuery after await error | Vue context lost after await | Put all useQuery calls before any await |
| Immediate refetch after hydration | staleTime too low | Set appropriate staleTime value |
## Key Points
1. Suspense + SSR has known edge cases - test thoroughly
2. Safari has slower chunk loading that triggers more hydration issues
3. With data-fetching libraries, ensure queries are set up before awaiting suspense
4. Consider ClientOnly wrappers for non-critical async content
5. Set appropriate staleTime to prevent unnecessary refetches after hydration
6. Use skeleton screens that match server-rendered content structure
## References
- [Vue.js Suspense Documentation](https://vuejs.org/guide/built-ins/suspense)
- [Vue Issue #6638 - Suspense hydration](https://github.com/vuejs/core/issues/6638)
- [Vue Issue #7672 - defineAsyncComponent SSR](https://github.com/vuejs/core/issues/7672)
- [TanStack Query SSR Discussion](https://github.com/TanStack/query/discussions/4870)
@@ -0,0 +1,144 @@
# Tailwind CSS Dynamic Class Generation
## Rule
Never construct Tailwind CSS class names dynamically using string concatenation or template literals. Tailwind's build process cannot detect dynamically generated class names, causing styles to be missing in production.
## Why This Matters
- Tailwind uses static analysis at build time to determine which CSS classes to include
- Dynamically constructed class names (e.g., `bg-${color}-500`) are invisible to Tailwind's scanner
- Classes work in development with JIT but fail silently in production builds
- This is a common source of "it works locally but not in production" bugs
## Bad Code
```vue
<script setup>
const props = defineProps({
color: String, // 'red', 'blue', 'green'
size: String // 'sm', 'md', 'lg'
})
</script>
<template>
<!-- WRONG: Tailwind cannot detect these classes -->
<div :class="`bg-${color}-500 text-${size}`">
Content
</div>
<!-- WRONG: String concatenation -->
<div :class="'p-' + padding">
Content
</div>
<!-- WRONG: Template literal in array -->
<div :class="[`gap-x-${spacing}`]">
Content
</div>
</template>
```
## Good Code
```vue
<script setup>
const props = defineProps({
color: String,
size: String
})
// Use a mapping object with complete class names
const colorClasses = {
red: 'bg-red-500',
blue: 'bg-blue-500',
green: 'bg-green-500'
}
const sizeClasses = {
sm: 'text-sm p-2',
md: 'text-base p-4',
lg: 'text-lg p-6'
}
</script>
<template>
<!-- CORRECT: Full class names that Tailwind can detect -->
<div :class="[colorClasses[color], sizeClasses[size]]">
Content
</div>
</template>
```
## Using Conditional Objects
```vue
<script setup>
const props = defineProps({
variant: String // 'primary', 'secondary', 'danger'
})
</script>
<template>
<!-- CORRECT: All class names are complete strings -->
<button :class="{
'bg-blue-500 hover:bg-blue-600': variant === 'primary',
'bg-gray-500 hover:bg-gray-600': variant === 'secondary',
'bg-red-500 hover:bg-red-600': variant === 'danger'
}">
Click me
</button>
</template>
```
## Safelist for Truly Dynamic Classes
If you must use dynamic classes, add them to Tailwind's safelist:
```javascript
// tailwind.config.js
module.exports = {
safelist: [
'bg-red-500',
'bg-blue-500',
'bg-green-500',
// Or use patterns (use sparingly - increases bundle size)
{
pattern: /bg-(red|blue|green)-(100|500|900)/
}
]
}
```
## Alternative: CSS Custom Properties
For truly dynamic values, use CSS custom properties:
```vue
<script setup>
const props = defineProps({
customColor: String // Any hex color
})
</script>
<template>
<!-- Use CSS variable for truly dynamic values -->
<div
class="dynamic-bg"
:style="{ '--dynamic-color': customColor }"
>
Content
</div>
</template>
<style>
.dynamic-bg {
background-color: var(--dynamic-color);
}
</style>
```
## References
- [Tailwind CSS Dynamic Class Names](https://tailwindcss.com/docs/content-configuration#dynamic-class-names)
- [Tailwind Safelist](https://tailwindcss.com/docs/content-configuration#safelisting-classes)
@@ -0,0 +1,191 @@
---
title: Scoped Styles May Not Apply to Teleported Content
impact: MEDIUM
impactDescription: Scoped styles can fail to apply to teleported elements due to data attribute limitations
type: gotcha
tags: [vue3, teleport, scoped-styles, css]
---
# Scoped Styles May Not Apply to Teleported Content
**Impact: MEDIUM** - When using scoped styles with Teleport, the styles may not apply correctly to teleported elements. This is a known limitation related to how Vue's scoped style attributes work with elements rendered outside the component's DOM tree.
## Task Checklist
- [ ] Test scoped styles on teleported content
- [ ] Use `:deep()` selector or non-scoped styles for teleported content
- [ ] Consider CSS modules as an alternative
- [ ] Keep teleported content styles in a separate non-scoped style block
**Problem - Scoped Styles Not Applied:**
```vue
<template>
<Teleport to="body">
<div class="modal">
<p class="modal-text">This text may not be styled!</p>
</div>
</Teleport>
</template>
<style scoped>
/* These styles may NOT apply to teleported content */
.modal {
background: white;
padding: 20px;
}
.modal-text {
color: blue; /* May not work */
}
</style>
```
**Solution 1 - Use Non-Scoped Styles for Teleported Content:**
```vue
<template>
<Teleport to="body">
<div class="my-modal">
<p class="my-modal-text">This text will be styled</p>
</div>
</Teleport>
</template>
<style scoped>
/* Component-specific styles */
.button { color: blue; }
</style>
<style>
/* Non-scoped styles for teleported content */
/* Use specific class names to avoid conflicts */
.my-modal {
background: white;
padding: 20px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.my-modal-text {
color: blue;
}
</style>
```
**Solution 2 - Use :deep() Selector:**
```vue
<template>
<Teleport to="body">
<div class="modal">
<p class="modal-text">Styled with :deep()</p>
</div>
</Teleport>
</template>
<style scoped>
:deep(.modal) {
background: white;
padding: 20px;
}
:deep(.modal-text) {
color: blue;
}
</style>
```
**Solution 3 - CSS Modules:**
```vue
<template>
<Teleport to="body">
<div :class="$style.modal">
<p :class="$style.modalText">Styled with CSS modules</p>
</div>
</Teleport>
</template>
<style module>
.modal {
background: white;
padding: 20px;
}
.modalText {
color: blue;
}
</style>
```
## Multi-Root Components with Teleport
Using Teleport as one of multiple root nodes causes additional issues:
```vue
<template>
<!-- Multi-root component -->
<button @click="open = true">Open</button>
<Teleport to="body">
<div class="modal">Content</div>
</Teleport>
</template>
<!-- Warning: class/style attributes may not be inherited -->
```
Pass classes explicitly to avoid inheritance issues:
```vue
<template>
<button @click="open = true">Open</button>
<Teleport to="body">
<div :class="['modal', $attrs.class]" :style="$attrs.style">
Content
</div>
</Teleport>
</template>
```
## Best Practice: Dedicated Modal Styles
Create a dedicated stylesheet for modal/overlay components:
```css
/* modal-styles.css */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
}
.modal-content {
background: white;
border-radius: 8px;
padding: 24px;
max-width: 500px;
width: 90%;
}
```
```vue
<script setup>
import './modal-styles.css'
</script>
<template>
<Teleport to="body">
<div v-if="open" class="modal-overlay">
<div class="modal-content">
<slot />
</div>
</div>
</Teleport>
</template>
```
## Reference
- [Vue.js SFC CSS Features - Scoped CSS](https://vuejs.org/api/sfc-css-features.html#scoped-css)
- [GitHub Issue #2047 - Scoped styles and teleport](https://github.com/vuejs/core/issues/2047)
@@ -0,0 +1,152 @@
---
title: Handle Teleport SSR Hydration Carefully
impact: HIGH
impactDescription: Teleported content causes hydration mismatches in SSR/SSG applications
type: gotcha
tags: [vue3, teleport, ssr, nuxt, hydration]
---
# Handle Teleport SSR Hydration Carefully
**Impact: HIGH** - Teleports require special handling during SSR. The teleported content is not part of the server-rendered HTML string, causing hydration mismatches that can break the application or cause content to disappear.
This is a critical issue for Nuxt, Quasar SSR, and custom Vue SSR setups.
## Task Checklist
- [ ] Wrap Teleport in `<ClientOnly>` component (Nuxt) for client-only rendering
- [ ] Use conditional rendering based on mount state for non-Nuxt SSR
- [ ] Use `data-allow-mismatch` attribute in Vue 3.5+ when intentional
- [ ] Test SSR applications thoroughly for hydration issues
**Problem - SSR Hydration Mismatch:**
```vue
<template>
<!-- Server renders nothing for teleported content -->
<!-- Client expects teleported content at #modals -->
<!-- = Hydration mismatch -->
<Teleport to="#modals">
<div v-if="showModal" class="modal">
Modal content
</div>
</Teleport>
</template>
```
Common error messages:
```
[Vue warn]: Hydration children mismatch in <div>:
server rendered element contains fewer child nodes than client vdom.
```
**Solution 1 - Nuxt ClientOnly:**
```vue
<template>
<button @click="showModal = true">Open Modal</button>
<!-- Only render on client, avoiding SSR -->
<ClientOnly>
<Teleport to="body">
<div v-if="showModal" class="modal">
Modal content
</div>
</Teleport>
</ClientOnly>
</template>
```
**Solution 2 - Manual Client Detection:**
```vue
<template>
<button @click="showModal = true">Open Modal</button>
<!-- Only render after component mounts on client -->
<Teleport v-if="isMounted" to="body">
<div v-if="showModal" class="modal">
Modal content
</div>
</Teleport>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const showModal = ref(false)
const isMounted = ref(false)
onMounted(() => {
isMounted.value = true
})
</script>
```
**Solution 3 - Vue 3.5+ data-allow-mismatch:**
```vue
<template>
<!-- Suppress hydration warnings for intentional mismatches -->
<div data-allow-mismatch>
<Teleport to="body">
<div v-if="showModal" class="modal">
Modal content
</div>
</Teleport>
</div>
</template>
```
## SSR with Multiple Teleports
Multiple teleports to the same target can cause additional hydration issues:
```vue
<!-- Parent.vue -->
<template>
<!-- First teleport -->
<Teleport to="#modals">
<NotificationBanner />
</Teleport>
<ChildComponent />
</template>
<!-- ChildComponent.vue -->
<template>
<!-- Second teleport to same target - order matters! -->
<Teleport to="#modals">
<Modal />
</Teleport>
</template>
```
For SSR, ensure consistent ordering or wrap each in `ClientOnly`.
## Element Plus and UI Library SSR
Many UI libraries use Teleport internally. Element Plus components that use Teleport include:
- ElDialog
- ElDrawer
- ElTooltip
- ElDropdown
- ElSelect
- ElDatePicker
```vue
<template>
<!-- These need special SSR handling -->
<ClientOnly>
<ElDialog v-model="visible">
Dialog content
</ElDialog>
</ClientOnly>
</template>
```
## Known Vue Issues
- Disabled teleports in fragments can cause hydration mismatches (Vue issue #6152)
- Nested teleports may cause app to break on hydration (Vue issue #5242)
## Reference
- [Vue.js SSR - Teleports](https://vuejs.org/guide/scaling-up/ssr.html#teleports)
- [Element Plus SSR Guide](https://element-plus.org/en-US/guide/ssr.html)
- [Nuxt ClientOnly Component](https://nuxt.com/docs/api/components/client-only)
@@ -0,0 +1,113 @@
---
title: Teleport Target Must Exist Before Mount
impact: HIGH
impactDescription: Teleport will fail silently or throw errors if target element doesn't exist when component mounts
type: gotcha
tags: [vue3, teleport, modal, dom, lifecycle]
---
# Teleport Target Must Exist Before Mount
**Impact: HIGH** - The teleport `to` target must already exist in the DOM when the `<Teleport>` component is mounted. If the target doesn't exist, Vue will throw an error and the teleported content won't render.
This is a common source of bugs when using modals, tooltips, or other teleported UI elements, especially when targeting Vue-rendered elements.
## Task Checklist
- [ ] Ensure teleport target exists in the DOM before `<Teleport>` mounts
- [ ] Place teleport containers (e.g., `#modals`, `#tooltips`) in `index.html` outside the Vue app
- [ ] If targeting Vue-rendered elements, ensure they mount before the Teleport
- [ ] Use Vue 3.5+ `defer` prop when target is rendered later in the same component tree
**Incorrect:**
```vue
<template>
<!-- ERROR: Target doesn't exist yet when Teleport mounts -->
<Teleport to="#modal-container">
<div class="modal">Modal content</div>
</Teleport>
<!-- Target is defined after the Teleport -->
<div id="modal-container"></div>
</template>
```
**Correct - Option 1: External container in index.html:**
```html
<!-- index.html -->
<body>
<div id="app"></div>
<!-- Container exists before Vue app mounts -->
<div id="modals"></div>
<div id="tooltips"></div>
</body>
```
```vue
<template>
<!-- Safe: #modals exists before any Vue component mounts -->
<Teleport to="#modals">
<div v-if="showModal" class="modal">Modal content</div>
</Teleport>
</template>
```
**Correct - Option 2: Teleport to body:**
```vue
<template>
<!-- Safe: body always exists -->
<Teleport to="body">
<div v-if="showModal" class="modal">Modal content</div>
</Teleport>
</template>
```
**Correct - Option 3: Vue 3.5+ defer prop:**
```vue
<template>
<!-- Works in Vue 3.5+: defer resolves target after other parts mount -->
<Teleport defer to="#late-container">
<div class="modal">Modal content</div>
</Teleport>
<!-- Target rendered later in template -->
<div id="late-container"></div>
</template>
```
## Defer Prop Limitations (Vue 3.5+)
The `defer` prop only waits for elements rendered in the **same mount/update tick**:
```vue
<template>
<!-- ERROR: defer won't help if target mounts asynchronously -->
<Teleport defer to="#async-container">
<div>Content</div>
</Teleport>
<!-- If this component loads asynchronously, defer won't work -->
<Suspense>
<AsyncComponent /> <!-- Contains #async-container -->
</Suspense>
</template>
```
## Common Patterns
### Recommended: Centralized Teleport Containers
```html
<!-- index.html -->
<body>
<div id="app"></div>
<!-- Teleport destinations outside Vue app -->
<div id="modals" aria-live="polite"></div>
<div id="notifications" aria-live="assertive"></div>
<div id="tooltips"></div>
</body>
```
## Reference
- [Vue.js Teleport - Using with Vue-rendered Targets](https://vuejs.org/guide/built-ins/teleport.html#using-with-vue-rendered-targets)
- [Vue.js Teleport - Deferred Teleport](https://vuejs.org/guide/built-ins/teleport.html#deferred-teleport)
@@ -0,0 +1,114 @@
---
title: Template Expressions Must Be Single Expressions
impact: MEDIUM
impactDescription: Using statements instead of expressions in templates causes compilation errors
type: capability
tags: [vue3, template, expressions, interpolation, syntax]
---
# Template Expressions Must Be Single Expressions
**Impact: MEDIUM** - Vue templates only support single JavaScript expressions, not statements. Using variable declarations, if statements, or multiple statements will cause template compilation errors.
Template interpolation `{{ }}` and directive bindings evaluate JavaScript expressions that produce a value. Statements like `if`, `for`, variable declarations, or multi-line code blocks are not allowed.
## Task Checklist
- [ ] Use only single expressions in `{{ }}` interpolation
- [ ] Use ternary operators instead of if/else statements
- [ ] Move complex logic to computed properties or methods
- [ ] Avoid variable declarations in templates
- [ ] Use `v-if`/`v-else` directives for conditional rendering
**Incorrect:**
```vue
<template>
<!-- ERROR: Variable declaration is a statement, not expression -->
<p>{{ var greeting = 'Hello' }}</p>
<p>{{ let x = 1 }}</p>
<p>{{ const name = 'Vue' }}</p>
<!-- ERROR: if statement not allowed -->
<p>{{ if (ok) { return message } }}</p>
<p>{{ if (user) return user.name }}</p>
<!-- ERROR: Multiple statements not allowed -->
<p>{{ count++; return count }}</p>
<p>{{ items.push(newItem); items.length }}</p>
<!-- ERROR: for/while loops not allowed -->
<p>{{ for (let i = 0; i < 5; i++) { } }}</p>
</template>
```
**Correct:**
```vue
<template>
<!-- OK: Simple expressions -->
<p>{{ message }}</p>
<p>{{ count + 1 }}</p>
<p>{{ items.length }}</p>
<!-- OK: Ternary operators for conditionals -->
<p>{{ ok ? 'YES' : 'NO' }}</p>
<p>{{ user ? user.name : 'Guest' }}</p>
<p>{{ score >= 60 ? 'Pass' : 'Fail' }}</p>
<!-- OK: Method/function calls -->
<p>{{ formatDate(date) }}</p>
<p>{{ items.filter(i => i.active).length }}</p>
<!-- OK: Chained expressions -->
<p>{{ message.split('').reverse().join('') }}</p>
<!-- OK: Template literals -->
<p>{{ `Hello, ${name}!` }}</p>
<!-- OK: Object/array expressions -->
<p>{{ { name: 'Vue', version: 3 } }}</p>
</template>
<script setup>
import { ref, computed } from 'vue'
const ok = ref(true)
const message = ref('Hello')
const user = ref({ name: 'Alice' })
const score = ref(85)
// Move complex logic to computed properties
const greeting = computed(() => {
if (user.value) {
return `Welcome back, ${user.value.name}!`
}
return 'Hello, Guest!'
})
// Or use methods for reusable logic
function formatDate(date) {
return new Date(date).toLocaleDateString()
}
</script>
```
## Use Directives for Control Flow
```vue
<template>
<!-- Instead of if/else in expressions, use v-if/v-else -->
<p v-if="user">Welcome, {{ user.name }}!</p>
<p v-else>Please log in</p>
<!-- Instead of loops in expressions, use v-for -->
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<!-- Conditional display without removing from DOM -->
<p v-show="isVisible">This toggles visibility</p>
</template>
```
## Reference
- [Vue.js Template Syntax - Using JavaScript Expressions](https://vuejs.org/guide/essentials/template-syntax.html#using-javascript-expressions)
- [Vue.js Conditional Rendering](https://vuejs.org/guide/essentials/conditional.html)
@@ -0,0 +1,187 @@
---
title: Template Functions Must Be Pure Without Side Effects
impact: MEDIUM
impactDescription: Functions with side effects in templates cause unpredictable behavior on every re-render
type: efficiency
tags: [vue3, template, functions, performance, side-effects]
---
# Template Functions Must Be Pure Without Side Effects
**Impact: MEDIUM** - Functions called in templates execute on every component re-render. Functions with side effects (modifying data, API calls, logging) will cause unpredictable behavior, performance issues, and difficult-to-debug bugs.
Template expressions including function calls are evaluated whenever the component updates. This makes them unsuitable for operations that should only happen once or that modify state.
## Task Checklist
- [ ] Keep template functions pure (same input = same output)
- [ ] Never modify reactive state inside template functions
- [ ] Never make API calls or async operations in template functions
- [ ] Move side effects to event handlers, watchers, or lifecycle hooks
- [ ] Use computed properties for derived values instead of functions when possible
- [ ] Avoid expensive computations; use computed properties for caching
**Incorrect:**
```vue
<template>
<!-- BAD: Modifies state on every render -->
<p>{{ incrementAndGet() }}</p>
<!-- BAD: API call on every render -->
<div>{{ fetchUserName() }}</div>
<!-- BAD: Logging side effect -->
<span>{{ logAndFormat(date) }}</span>
<!-- BAD: Expensive computation without caching -->
<ul>
<li v-for="item in filterAndSort(items)" :key="item.id">
{{ item.name }}
</li>
</ul>
<!-- BAD: Random values change on every render -->
<p>{{ getRandomGreeting() }}</p>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
const items = ref([/* large array */])
// BAD: Has side effect - modifies state
function incrementAndGet() {
count.value++ // Side effect!
return count.value
}
// BAD: Async operation in template
async function fetchUserName() {
const res = await fetch('/api/user') // Side effect!
return (await res.json()).name
}
// BAD: Logging is a side effect
function logAndFormat(date) {
console.log('Formatting date:', date) // Side effect!
return new Date(date).toLocaleDateString()
}
// BAD: Expensive, runs every render without caching
function filterAndSort(items) {
return items
.filter(i => i.active)
.sort((a, b) => a.name.localeCompare(b.name))
}
// BAD: Non-deterministic
function getRandomGreeting() {
const greetings = ['Hello', 'Hi', 'Hey']
return greetings[Math.floor(Math.random() * greetings.length)]
}
</script>
```
**Correct:**
```vue
<template>
<!-- OK: Pure formatting function -->
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<!-- OK: Data fetched via lifecycle/watcher -->
<div>{{ userName }}</div>
<!-- OK: Pure function, no side effects -->
<span>{{ formatDate(date) }}</span>
<!-- OK: Computed property caches result -->
<ul>
<li v-for="item in filteredAndSortedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<!-- OK: Random value set once -->
<p>{{ greeting }}</p>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
const count = ref(0)
const userName = ref('')
const date = ref(new Date())
const items = ref([/* large array */])
// Side effects in event handlers
function increment() {
count.value++
}
// Fetch data in lifecycle hook
onMounted(async () => {
const res = await fetch('/api/user')
userName.value = (await res.json()).name
})
// Pure function - same input, same output
function formatDate(date) {
return new Date(date).toLocaleDateString()
}
// Computed property - cached, only recalculates when dependencies change
const filteredAndSortedItems = computed(() => {
return items.value
.filter(i => i.active)
.sort((a, b) => a.name.localeCompare(b.name))
})
// Set random value once, not on every render
const greetings = ['Hello', 'Hi', 'Hey']
const greeting = ref(greetings[Math.floor(Math.random() * greetings.length)])
</script>
```
## Pure Function Guidelines
A pure function:
1. Given the same inputs, always returns the same output
2. Does not modify any external state
3. Does not perform I/O operations (network, console, file system)
4. Does not depend on mutable external state
```javascript
// PURE - safe for templates
function formatCurrency(amount, currency = 'USD') {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount)
}
function fullName(first, last) {
return `${first} ${last}`
}
function isExpired(date) {
return new Date(date) < new Date()
}
// IMPURE - unsafe for templates
function logAndReturn(value) {
console.log(value) // I/O
return value
}
function getFromLocalStorage(key) {
return localStorage.getItem(key) // External state
}
function updateAndReturn(obj, key, value) {
obj[key] = value // Mutation
return obj
}
```
## Reference
- [Vue.js Template Syntax - Calling Functions](https://vuejs.org/guide/essentials/template-syntax.html#calling-functions)
- [Vue.js Computed Properties](https://vuejs.org/guide/essentials/computed.html)

Some files were not shown because too many files have changed in this diff Show More