
Vue Debug Guides
- 14.5k installs
- 2.8k repo stars
- Updated May 30, 2026
- hyf0/vue-skills
vue-debug-guides is an agent skill documented in hyf0/vue-skills.
About
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
- Use Key Attribute to Force Re-render Animations
- [ ] 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
Vue Debug Guides by the numbers
- 14,500 all-time installs (skills.sh)
- +72 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #39 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Security screen: SAFE risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
vue-debug-guides capabilities & compatibility
- Capabilities
- use key attribute to force re render animations · [ ] add `:key` to elements that should animate w · [ ] use unique, changing values for keys (not in · [ ] for route transitions, add `:key="$route.ful · [ ] apply `v auto animate` to the parent element
- Use cases
- documentation
What vue-debug-guides says it does
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.
It considers the old element and new element as different 2.
The old element is removed (triggering leave animation) 3.
npx skills add https://github.com/hyf0/vue-skills --skill vue-debug-guidesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 14.5k |
|---|---|
| repo stars | ★ 2.8k |
| Security audit | 2 / 3 scanners passed |
| Last updated | May 30, 2026 |
| Repository | hyf0/vue-skills ↗ |
What problem does vue-debug-guides solve for developers using this skill?
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 a
Who is it for?
Developers who need vue-debug-guides patterns described in the cached skill documentation.
Skip if: Skip when docs are empty or the task is outside the skill's documented scope.
When should I use this skill?
User asks about vue-debug-guides or triggers the skill by name.
What you get
Actionable workflows and conventions from SKILL.md for vue-debug-guides.
- :key binding fixes
- working list transitions
- AutoAnimate-compatible DOM updates
By the numbers
- Guide impact rating: MEDIUM for missing :key animation failures
Files
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
:keyto 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-animateto the parent element of keyed children
Problematic Code:
<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:
<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
<template>
<div v-auto-animate>
<h1 :key="title">{{ title }}</h1>
<p :key="description">{{ description }}</p>
</div>
</template>Animating Dynamic Components
<template>
<div v-auto-animate>
<component :is="currentComponent" :key="currentComponent" />
</div>
</template>Animating Route Transitions
<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:
<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 changin
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
:keyto 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-animateto the parent element of keyed children
Problematic Code:
<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:
<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
<template>
<div v-auto-animate>
<h1 :key="title">{{ title }}</h1>
<p :key="description">{{ description }}</p>
</div>
</template>Animating Dynamic Components
<template>
<div v-auto-animate>
<component :is="currentComponent" :key="currentComponent" />
</div>
</template>Animating Route Transitions
<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:
<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
<!-- Be cautious with complex components -->
<ComplexDashboard :key="refreshTrigger" />
<!-- This destroys and recreates the entire dashboard! -->Reference
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: autofor 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:
<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:
<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
<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
<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
<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
/* 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)
<!-- 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
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
<script setup>
import { defineAsyncComponent } from 'vue'
// No error handling - fails silently
const AsyncWidget = defineAsyncComponent(() =>
import('./Widget.vue')
)
</script><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
<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><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><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
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
<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
<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:
<!-- 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
<!-- 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
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: falsewhen 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:
<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):
<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):
<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>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
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
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:
<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
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
<!-- 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
<!-- 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
<!-- 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
<!-- 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:
<!-- 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
<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
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-valuefor form submissions - it won't be sent - [ ] Use radio buttons when you need to submit one of exactly two values
- [ ] Remember
true-value/false-valueare for JavaScript state only - [ ] For form submissions with custom values, handle the transformation server-side or in submit handler
Problem - false-value not submitted:
<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:
<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):
<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:
<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
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
onBeforeUnmountif cleanup must happen before DOM removal
Incorrect:
// 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)
})
}
}// 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:
// 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)
})
}
}// 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
// 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
// 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
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
defineEmitsin child components - [ ] Emit click events from child component when needed
- [ ] Understand that single-root components automatically forward attrs to root
- [ ] Remove
.nativemodifier when migrating from Vue 2 to Vue 3 - [ ] For multi-root components, explicitly bind
$attrsor emit events
Incorrect:
<!-- WRONG: Expecting native click to work on custom component -->
<template>
<MyButton @click="handleClick">Click me</MyButton>
<!-- This may not work as expected! -->
</template><!-- 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><!-- 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:
<!-- 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><!-- 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><!-- 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
// 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
// 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 clickComposition API Emit Pattern
<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
<!-- 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
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:
// main.js
import { createApp } from 'vue'
import Button from './components/Button.vue'
const app = createApp(App)
app.component('Button', Button) // Global Button<!-- 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><!-- 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:
// 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)<!-- 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:
<script setup>
// Explicit alias to avoid confusion
import { default as LocalButton } from './Button.vue'
</script>
<template>
<LocalButton>Local version</LocalButton>
</template><!-- 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
<!-- 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
<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
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:
<!-- 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><!-- 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:
<!-- 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><!-- 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><!-- 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>// 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:
<!-- 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
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:
// 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:
// 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:
/**
* 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
// 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
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>orsetup() - [ ] 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:
<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:
<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:
<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:
<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.
// 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
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:
// 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:
// 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:
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 againPattern: Returning Both State and Actions
// 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
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()insidewatchEffectcallbacks, not before - [ ] Similarly, access
.valueon refs inside watchEffect, not outside - [ ] For
watch(), use a getter function that callstoValue() - [ ] Test that composables update when their inputs change
Incorrect:
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:
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
// 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:
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:
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
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
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()andreactive()enable mutable state tracking - [ ] Use Vue's reactivity as intended: direct mutation with automatic tracking
Incorrect:
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:
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
// 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 libThe Vue Mental Model
// 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 patternReference
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):
<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:
<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:
<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):
// 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
// 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
<!-- 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
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:
// 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:
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
// 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 casesWhen Vue Patterns Differ
// 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
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]orslice()to copy arrays - [ ] Prefer non-mutating alternatives when available
- [ ] Be aware which array methods mutate vs return new arrays
Incorrect:
<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:
<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:
// 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:
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
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:
<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:
<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:
// 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
// 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
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:
<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><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:
<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:
<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:
<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
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:
<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:
<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
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:
<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><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:
<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><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:
<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
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.configproperties before mount() - [ ] Call
.mount()as the final step in app initialization
Incorrect:
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:
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
// 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 endReference
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
emitsoption 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:
<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:
<script setup>
const emit = defineEmits(['submit', 'cancel', 'update'])
function handleSubmit() {
emit('submit', formData)
}
function handleCancel() {
emit('cancel')
}
</script>Correct - Options API:
export default {
emits: ['submit', 'cancel', 'update'],
methods: {
handleSubmit() {
this.$emit('submit', this.formData)
}
}
}TypeScript Typed Emits
Correct - Type-based declaration (recommended for TypeScript):
<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+):
<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:
<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:
<!-- ParentComponent.vue -->
<ChildComponent @click="handleClick" /><!-- 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:
<script setup>
// Now Vue knows 'click' is a component event, not native
const emit = defineEmits(['click'])
</script>2. Self-Documentation
<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
<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
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:
<!-- 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><!-- 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:
<!-- 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><!-- 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><!-- 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.
// 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
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:
<!-- 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><!-- 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:
<!-- 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):
<!-- 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:
<!-- 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:
<!-- 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
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:
<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:
<script setup>
if (someCondition) {
// ERROR: Cannot use defineEmits in conditional
const emit = defineEmits(['eventA'])
} else {
const emit = defineEmits(['eventB'])
}
</script>Incorrect - Referencing local variables:
<script setup>
const eventNames = ['submit', 'cancel']
// ERROR: Cannot reference local variables
const emit = defineEmits(eventNames)
</script>Correct Usage
Correct - Top level declaration:
<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:
<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):
<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:
<script setup>
const emit = defineEmits(['submit', 'cancel', 'validate'])
// Pass emit to composable
const { handleSubmit, handleCancel } = useFormEvents(emit)
</script>// 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:
// eslint.config.js
export default [
{
rules: {
'vue/valid-define-emits': 'error'
}
}
]This rule reports:
defineEmitsused inside functionsdefineEmitsreferencing local variables- Multiple
defineEmitscalls in the same component defineEmitsused outside<script setup>
Reference
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:
<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:
<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)
<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:
<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:
<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:
<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:
<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:
<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
Related skills
How it compares
Use vue-debug-guides for targeted Vue 3 DOM reuse and :key gotchas instead of broad Flutter or CSS animation skills.
FAQ
What does vue-debug-guides do?
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 t
When should I use vue-debug-guides?
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 a
Is vue-debug-guides safe to install?
Review the Security Audits panel on this page before installing in production.