编辑 | blame | 历史 | 原始文档

---
name: vue-component
description: 创建新的 Vue 3 组件,包含 TypeScript 类型定义和最佳实践

allowed_tools: ["Bash", "Read", "Write", "Grep", "Glob"]

/vue-component

创建新的 Vue 3 组件时使用此工作流。

目标

创建一个结构良好的 Vue 3 组件,包含 TypeScript 类型、正确的 props/emit 定义,并遵循项目规范。

常用文件

  • src/components/**/*.vue
  • src/views/**/*.vue
  • src/**/components/*.vue

建议步骤

  1. 根据作用域确定组件位置(全局组件 vs 功能组件)
  2. 创建 .vue 文件,使用 <script setup lang="ts">
  3. 定义 Props 和 Emits 的 TypeScript 接口
  4. 使用 Composition API 实现组件逻辑
  5. 添加模板和正确的绑定
  6. 如需要,添加 scoped 样式
  7. 导出组件供使用

组件模板

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

// Props 定义
interface Props {
  title: string;
  disabled?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
});

// Emits 定义
interface Emits {
  (e: 'click', value: string): void;
}

const emit = defineEmits<Emits>();

// 响应式状态
const isActive = ref(false);

// 方法
const handleClick = () => {
  if (!props.disabled) {
    isActive.value = !isActive.value;
    emit('click', props.title);
  }
};
</script>

<template>
  <div
    class="component-name"
    :class="{ 'is-active': isActive, 'is-disabled': disabled }"
    @click="handleClick"
  >
    <span>{{ title }}</span>
    <slot />
  </div>
</template>

<style scoped>
.component-name {
  /* 样式 */
}
</style>

典型提交信息

  • feat: add [组件名] component
  • feat: implement [组件名] for [功能名]