关于 vue-best-practices
vue-best-practices 是面向 Vue 3 开发者的参考技能,按 TypeScript、组件、工具链和测试等主题整理实践建议,也涵盖 Vue 3.5 模式与常见错误。
主要功能
- 01TypeScript 与组件类型
- 02Volar 和 IDE 配置
- 03Vue 组件模式
- 04工具链与 HMR 指引
- 05Pinia 和路由测试
- 06避免常见错误
适用场景
- 01选择响应式 props 模式
- 02为 Vue 组件 props 定义类型
- 03配置 Volar 模板检查
- 04设置 Pinia Store 测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ ejirocodes/ agent-skills --skill vue-best-practices安装后在 Claude Code 中输入/vue-best-practices确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/components.mdtesting.mdtooling.mdtypescript.mdvolar.md详细介绍
Vue 3 最佳实践
快速参考
| 主题 | 适用场景 | 参考 |
|---|---|---|
| TypeScript | 提取 Props、泛型组件、useTemplateRef、JSDoc、响应式 Props 解构 | typescript.md |
| Volar | IDE 配置、strictTemplates、CSS 模块、指令注释、Volar 3.0 迁移 | volar.md |
| 组件 | defineModel、深度侦听、onWatcherCleanup、useId、延迟 teleport | components.md |
| 工具链 | moduleResolution、HMR SSR、重复插件检测 | tooling.md |
| 测试 | Pinia store 模拟、setup store、Vue Router 类型化参数 | testing.md |
核心模式
提取组件 Props
import type { ComponentProps } from 'vue-component-type-helpers'
import MyButton from './MyButton.vue'
type Props = ComponentProps<typeof MyButton>
响应式 Props 解构(Vue 3.5+)
<script setup lang="ts">
// Destructured props are reactive - preferred in Vue 3.5+
const { name, count = 0 } = defineProps<{ name: string; count?: number }>()
</script>
useTemplateRef(Vue 3.5+)
<script setup lang="ts">
import { useTemplateRef, onMounted } from 'vue'
const inputRef = useTemplateRef('input') // Auto-typed
onMounted(() => inputRef.value?.focus())
</script>
<template><input ref="input" /></template>
onWatcherCleanup(Vue 3.5+)
import { watch, onWatcherCleanup } from 'vue'
watch(query, async (q) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort())
await fetch(`/api?q=${q}`, { signal: controller.signal })
})
带 Required 的 defineModel
// Returns Ref<Item> instead of Ref<Item | undefined>
const model = defineModel<Item>({ required: true })
使用数值深度进行深度侦听
// Vue 3.5+ - watch array mutations without full traversal
watch(items, handler, { deep: 1 })
Pinia Store 测试设置
import { createTestingPinia } from '@pinia/testing'
import { vi } from 'vitest'
mount(Component, {
global: {
plugins: [createTestingPinia({ createSpy: vi.fn })]
}
})
常见错误
- 使用
InstanceType<typeof Component>['$props']- 改用ComponentProps - 在 createTestingPinia 中缺少
createSpy- @pinia/testing 1.0+ 必须提供 - 对联合类型使用
withDefaults- 改用响应式 Props 解构 - 在错误的 tsconfig 中设置
strictTemplates- 添加到tsconfig.app.json,而不是根目录配置 - 在 Volar 3.0 中使用 ts_ls - 改用 vtsls(Neovim)
- 对大型结构使用
deep: true- 使用数值深度以提升性能 - 直接侦听解构后的 props - 用 getter 包装:
watch(() => count, ...) - SSR 中使用随机 ID - 使用
useId(),确保 ID 可安全用于水合
评论
支持 Markdown