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.

referencestesting.md

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

Testing Patterns

Table of Contents


Pinia Store Mocking

createTestingPinia creates a Pinia instance designed for unit tests that automatically mocks stores.

Important (@pinia/testing 1.0+): The createSpy option is REQUIRED when globals: true is not set in Vitest config. Omitting it throws: "You must configure the createSpy option."

Symptoms

  • "injection Symbol(pinia) not found" error
  • "You must configure the createSpy option" error
  • Actions not properly mocked
  • Store state not reset between tests

Basic Setup

import { mount } from '@vue/test-utils'
import { createTestingPinia } from '@pinia/testing'
import { vi } from 'vitest'
import MyComponent from './MyComponent.vue'
import { useCounterStore } from '@/stores/counter'

test('component uses store', async () => {
  const wrapper = mount(MyComponent, {
    global: {
      plugins: [
        createTestingPinia({
          createSpy: vi.fn,  // REQUIRED without globals: true
          initialState: {
            counter: { count: 10 }  // Set initial state
          }
        })
      ]
    }
  })

  // Get store instance AFTER mounting
  const store = useCounterStore()

  // Actions are automatically stubbed
  await wrapper.find('button').trigger('click')
  expect(store.increment).toHaveBeenCalled()
})

With globals: true in Vitest Config

If you have globals: true in your Vitest config, createSpy is auto-detected:

// vitest.config.ts
export default defineConfig({
  test: {
    globals: true  // Enables auto-detection of vi.fn
  }
})

// Test file - createSpy not needed
const pinia = createTestingPinia({
  initialState: { counter: { count: 5 } }
})

Custom Action Behavior

test('component handles async action', async () => {
  const wrapper = mount(MyComponent, {
    global: {
      plugins: [
        createTestingPinia({
          createSpy: vi.fn,
          stubActions: false  // Don't stub, use real actions
        })
      ]
    }
  })

  const store = useCounterStore()

  // Override specific action with mock implementation
  store.fetchData = vi.fn().mockResolvedValue({ items: [] })

  await wrapper.find('.load-button').trigger('click')
  expect(store.fetchData).toHaveBeenCalled()
})

Using vi.spyOn for More Control

test('action with custom mock', async () => {
  const wrapper = mount(MyComponent, {
    global: {
      plugins: [createTestingPinia({ createSpy: vi.fn })]
    }
  })

  const store = useCounterStore()

  // More control with spyOn
  const spy = vi.spyOn(store, 'increment')
  spy.mockImplementation(() => {
    store.count += 10  // Custom increment
  })

  await wrapper.find('button').trigger('click')
  expect(store.count).toBe(10)
})

Reset Between Tests

describe('Store Tests', () => {
  let pinia: ReturnType<typeof createTestingPinia>

  beforeEach(() => {
    pinia = createTestingPinia({
      createSpy: vi.fn
    })
  })

  afterEach(() => {
    vi.clearAllMocks()
  })

  test('test 1', () => { /* fresh pinia instance */ })
  test('test 2', () => { /* fresh pinia instance */ })
})

Including Pinia Plugins

import { myPiniaPlugin } from '@/plugins/pinia'

const pinia = createTestingPinia({
  createSpy: vi.fn,
  plugins: [myPiniaPlugin]  // Pass plugins here, not with .use()
})

Reference: Pinia Testing Guide


Testing Setup Stores

Setup stores (function-based) have special testing considerations because they don't have an options.actions object.

Direct Store Testing

import { setActivePinia, createPinia } from 'pinia'
import { useCounterStore } from '@/stores/counter'

describe('Counter Store', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
  })

  test('increments count', () => {
    const store = useCounterStore()
    expect(store.count).toBe(0)

    store.increment()
    expect(store.count).toBe(1)
  })

  test('computed values', () => {
    const store = useCounterStore()
    store.count = 5
    expect(store.doubleCount).toBe(10)
  })
})

Setup Store Definition

// stores/counter.ts
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)

  function increment() {
    count.value++
  }

  async function fetchCount() {
    const response = await fetch('/api/count')
    count.value = await response.json()
  }

  return { count, doubleCount, increment, fetchCount }
})

Component Testing with Setup Store

test('setup store in component', async () => {
  const pinia = createTestingPinia({
    createSpy: vi.fn,
    initialState: {
      counter: { count: 5 }
    }
  })

  const wrapper = mount(MyComponent, {
    global: { plugins: [pinia] }
  })

  const store = useCounterStore()
  expect(store.count).toBe(5)
  expect(store.doubleCount).toBe(10)

  // Action is stubbed by default
  await wrapper.find('button').trigger('click')
  expect(store.increment).toHaveBeenCalled()
})

Testing $subscribe

test('store subscription', async () => {
  setActivePinia(createPinia())
  const store = useCounterStore()

  const callback = vi.fn()
  store.$subscribe(callback)

  store.increment()

  expect(callback).toHaveBeenCalledWith(
    expect.objectContaining({ storeId: 'counter' }),
    expect.objectContaining({ count: 1 })
  )
})

Reference: Pinia Testing Guide


Vue Router Typed Params

With unplugin-vue-router, route.params becomes a union of ALL page param types. TypeScript cannot narrow this properly without help.

Symptoms

  • "Property 'id' does not exist on type 'RouteParams'"
  • route.params.id shows as string | undefined everywhere
  • Union type of all route params instead of specific route
  • Type narrowing with if (route.name === 'users-id') doesn't work

Root Cause

unplugin-vue-router generates a union type of all possible route params. TypeScript's control flow analysis can't narrow this union based on route name checks.

Fix

Option 1: Pass route path to useRoute (recommended)

// pages/users/[id].vue
import { useRoute } from 'vue-router/auto'

// Specify the route path for proper typing
const route = useRoute('/users/[id]')

// Now properly typed as { id: string }
console.log(route.params.id)  // string, not string | undefined

Option 2: Type assertion with specific route

import { useRoute } from 'vue-router'
import type { RouteLocationNormalized } from 'vue-router/auto-routes'

const route = useRoute() as RouteLocationNormalized<'/users/[id]'>
route.params.id  // Properly typed

Option 3: Define route-specific param type

// In your page component
interface UserRouteParams {
  id: string
}

const route = useRoute()
const { id } = route.params as UserRouteParams

Route Path Format

The route path matches the file path pattern:

File Path Route Path
pages/users/[id].vue /users/[id]
pages/posts/[slug]/comments.vue /posts/[slug]/comments
pages/[...path].vue /[...path]

Required tsconfig Settings

{
  "compilerOptions": {
    "moduleResolution": "bundler"
  }
}

Reference: unplugin-vue-router TypeScript docs


Automatic Route Typing with Volar Plugin

The sfc-typed-router Volar plugin automatically types useRoute() and $route in page components, eliminating the need for manual path specification.

Setup

Add to your tsconfig.json:

{
  "compilerOptions": {
    "rootDir": "."
  },
  "vueCompilerOptions": {
    "plugins": ["unplugin-vue-router/volar/sfc-typed-router"]
  }
}

How It Works

With the plugin enabled, useRoute() in a page component automatically uses the correct route type:

<!-- pages/users/[id].vue -->
<script setup lang="ts">
// No path needed - automatically typed based on file location
const route = useRoute()

// route.params.id is properly typed as string
console.log(route.params.id)
</script>

Benefits

  • No need to write useRoute('/users/[id]') in every page
  • $route in templates is also typed correctly
  • Works with both Composition API and Options API
  • Autocomplete for route params

Limitations

  • Only works in page components (files under pages/)
  • Non-page components still need explicit typing
  • Requires Volar and correct tsconfig setup

Reference: unplugin-vue-router Volar Plugin

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