Index of every page on this site: llms.txt
All skills
ejirocodes avatar

/vue-best-practices

@6e805e4
Run it yourself

Vue 3 and Vue.js best practices for TypeScript, vue-tsc, Volar, and component patterns. Use when writing, reviewing, or refactoring Vue 3 components with TypeScript, configuring Volar/vueCompilerOptions, extracting component types, working with defineModel/withDefaults, setting up Pinia store tests, or debugging Vue tooling issues. Triggers on Vue components, props extraction, wrapper components, template type checking, strictTemplates, vueCompilerOptions, Volar 3, CSS modules, fallthrough attributes, defineModel, withDefaults, deep watch, vue-router typed params, Pinia mocking, HMR SSR, moduleResolution bundler, useTemplateRef, onWatcherCleanup, useId, generic components, reactive props destructure.

Use this Skill: https://skilld.dev/gh/ejirocodes/agent-skills/vue-best-practices

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencestypescript.md

≈2.6k tokens on demand. Your agent reads this file only when SKILL.md points to it.

TypeScript Patterns

Table of Contents


Extract Component Props

Use vue-component-type-helpers to extract types from .vue components:

npm install -D vue-component-type-helpers
import type { ComponentProps, ComponentEmit, ComponentSlots, ComponentExposed } from 'vue-component-type-helpers'
import MyButton from './MyButton.vue'

type Props = ComponentProps<typeof MyButton>
type Emits = ComponentEmit<typeof MyButton>
type Slots = ComponentSlots<typeof MyButton>
type Exposed = ComponentExposed<typeof MyButton>

Wrapper Component Pattern

import type { ComponentProps } from 'vue-component-type-helpers'
import BaseButton from './BaseButton.vue'

type BaseProps = ComponentProps<typeof BaseButton>

interface Props extends BaseProps {
  size: 'sm' | 'md' | 'lg'
}

defineProps<Props>()

Do NOT Use

// ❌ Includes Vue internal properties (onUpdate:*, class, style, etc.)
type Props = InstanceType<typeof MyButton>['$props']

Vue's built-in ExtractPropTypes is for runtime props objects (props: { foo: String }), not for .vue components.

Reference: vue-component-type-helpers


Generic Components

Create type-safe generic components using the generic attribute on <script>.

Basic Generic Component

<script setup lang="ts" generic="T">
defineProps<{
  items: T[]
  selected?: T
}>()

defineEmits<{
  select: [item: T]
}>()
</script>

<template>
  <ul>
    <li v-for="item in items" @click="$emit('select', item)">
      <slot :item="item" />
    </li>
  </ul>
</template>

With Constraints

<script setup lang="ts" generic="T extends { id: string | number }">
defineProps<{
  items: T[]
  selectedId?: T['id']
}>()
</script>

Multiple Type Parameters

<script setup lang="ts" generic="T, U extends keyof T">
defineProps<{
  data: T
  field: U
}>()
</script>

Using Generic Components

<template>
  <!-- TypeScript infers T from items prop -->
  <GenericList :items="users" @select="handleUser">
    <template #default="{ item }">
      {{ item.name }} <!-- item is typed as User -->
    </template>
  </GenericList>
</template>

Reference: Vue TypeScript with Composition API


useTemplateRef Typing

Vue 3.5 introduced useTemplateRef() for cleaner template ref management with automatic type inference.

Basic Usage

<script setup lang="ts">
import { useTemplateRef, onMounted } from 'vue'

// Type is inferred as ShallowRef<HTMLInputElement | null>
const inputRef = useTemplateRef('input')

onMounted(() => {
  inputRef.value?.focus()
})
</script>

<template>
  <input ref="input" />
</template>

With Component Refs

<script setup lang="ts">
import { useTemplateRef } from 'vue'
import type { ComponentExposed } from 'vue-component-type-helpers'
import MyForm from './MyForm.vue'

// For generic components, use ComponentExposed
type FormExposed = ComponentExposed<typeof MyForm>
const formRef = useTemplateRef<InstanceType<typeof MyForm>>('form')

function submit() {
  formRef.value?.validate()
}
</script>

<template>
  <MyForm ref="form" />
</template>

In Composables

// composables/useChart.ts
import { useTemplateRef, onMounted, onUnmounted } from 'vue'

export function useChart(refName: string) {
  const canvasRef = useTemplateRef<HTMLCanvasElement>(refName)
  let chart: Chart | null = null

  onMounted(() => {
    if (canvasRef.value) {
      chart = new Chart(canvasRef.value, { /* config */ })
    }
  })

  onUnmounted(() => {
    chart?.destroy()
  })

  return { canvasRef, chart }
}

Note: With @vue/language-tools 2.1+, static template refs' types are automatically inferred. Manual typing is only needed for edge cases.

Reference: Vue Template Refs


JSDoc for Script Setup

<script setup> doesn't have an obvious place to attach JSDoc comments for the component itself. Use a dual-script pattern.

Problem

<script setup lang="ts">
/**
 * This comment doesn't appear in IDE hover or docs
 * @component
 */
import { ref } from 'vue'

const count = ref(0)
</script>

JSDoc comments inside <script setup> don't attach to the component export because there's no explicit export statement.

Solution

Use both <script> and <script setup> blocks:

<script lang="ts">
/**
 * A counter component that displays and increments a value.
 *
 * @example
 * ```vue
 * <Counter :initial="5" @update="handleUpdate" />
 * ```
 *
 * @component
 */
export default {}
</script>

<script setup lang="ts">
import { ref } from 'vue'

const props = defineProps<{
  /** Starting value for the counter */
  initial?: number
}>()

const emit = defineEmits<{
  /** Emitted when counter value changes */
  update: [value: number]
}>()

const count = ref(props.initial ?? 0)
</script>

What Gets Documented

Location Shows In
export default {} JSDoc Component import hover
defineProps JSDoc Prop hover in templates
defineEmits JSDoc Event handler hover

Reference: Vue Language Tools Discussion #5932


Reactive Props Destructure

Vue 3.5 stabilized Reactive Props Destructure, enabled by default. Variables destructured from defineProps are automatically reactive.

Basic Pattern

<script setup lang="ts">
// Destructured props are reactive - no ref() needed
const { name, count = 0 } = defineProps<{
  name: string
  count?: number
}>()

// Access directly in script
console.log(name, count)
</script>

<template>
  <!-- Access directly in template -->
  <div>{{ name }}: {{ count }}</div>
</template>

Watching Destructured Props

Wrap in a getter when watching or passing to composables:

const { count } = defineProps<{ count: number }>()

// ✅ Correct - wrap in getter
watch(() => count, (newVal) => {
  console.log('count changed:', newVal)
})

// ❌ Incorrect - loses reactivity
watch(count, handler) // Won't work as expected

With Default Values

<script setup lang="ts">
// Defaults work naturally with destructuring
const {
  title = 'Default Title',
  items = [],
  config = { debug: false }
} = defineProps<{
  title?: string
  items?: string[]
  config?: { debug: boolean }
}>()
</script>

Enable for Vue < 3.5

// vite.config.js
export default {
  plugins: [
    vue({
      script: {
        propsDestructure: true
      }
    })
  ]
}

Reference: Reactive Props Destructure RFC


withDefaults Union Types

Using withDefaults with union types like false | string may produce a Vue runtime warning "Missing required prop" even when a default is provided.

Symptoms

  • Vue warns "Missing required prop" despite default being set
  • Warning appears only with union types like false | string
  • TypeScript types are correct
  • Runtime value IS correct (the default is applied)

Problematic Pattern

// This produces a spurious warning (but works at runtime)
interface Props {
  value: false | string  // Union type
}

const props = withDefaults(defineProps<Props>(), {
  value: 'default'  // Runtime value IS correct, but Vue warns about missing prop
})

Fix

Option 1: Use Reactive Props Destructure (Vue 3.5+) - Recommended

<script setup lang="ts">
interface Props {
  value: false | string
}

// Preferred in Vue 3.5+
const { value = 'default' } = defineProps<Props>()
</script>

Option 2: Use runtime declaration

<script setup lang="ts">
const props = defineProps({
  value: {
    type: [Boolean, String] as PropType<false | string>,
    default: 'default'
  }
})
</script>

Option 3: Split into separate props

interface Props {
  enabled: boolean
  customValue?: string
}

const props = withDefaults(defineProps<Props>(), {
  enabled: false,
  customValue: 'default'
})

Reference: vuejs/core#12897


Strict Template Checking

By default, vue-tsc does not report errors for undefined components in templates. Enable strictTemplates to catch these issues during type checking.

Which tsconfig?

Add vueCompilerOptions to the tsconfig that includes Vue source files. In projects with multiple tsconfigs (like those created with create-vue), this is typically tsconfig.app.json, not the root tsconfig.json or tsconfig.node.json.

Incorrect (missing strict checking):

{
  "compilerOptions": {
    "strict": true
  }
  // vueCompilerOptions not configured - undefined components won't error
}

Correct (strict template checking enabled):

{
  "compilerOptions": {
    "strict": true
  },
  "vueCompilerOptions": {
    "strictTemplates": true
  }
}

Available Options

Option Default Effect
strictTemplates false Enables all checkUnknown* options below
checkUnknownComponents false Error on undefined/unregistered components
checkUnknownProps false Error on props not declared in component definition
checkUnknownEvents false Error on events not declared via defineEmits
checkUnknownDirectives false Error on unregistered custom directives

Granular Control

If strictTemplates is too strict, enable individual checks:

{
  "vueCompilerOptions": {
    "checkUnknownComponents": true,
    "checkUnknownProps": false
  }
}

Reference: Vue Compiler Options

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

1 warning2mo5 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides comprehensive best practices for Vue 3 development, including TypeScript integration, component design patterns, testing strategies using Pinia and Vitest, and tooling configuration for Vite and Volar. All referenced resources and packages are standard ecosystem tools from reputable sources.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

  • Runlayer9mo

    6/6 files flagged

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 6e805e4. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 10 months ago
metadata
{
  "author": "ejirocodes",
  "version": "1.0.0"
}

README badge

README badge for ejirocodes/agent-skills/vue-best-practices