К основному содержанию
скилл CX Codex

script-setup — скилл для Claude Code: синтаксис Vue 3 Composition API

Учит агента писать Vue 3-компоненты с <script setup> — без лишнего кода и явного return.

MIT 195 установок ★ 259 обновлён 2026-04-15

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add PatternsDev/skills --skill script-setup -a claude-code
Открыть на GitHub

Что делает script-setup

Скилл показывает агенту, как работать с <script setup> в однофайловых компонентах Vue 3. Весь код на верхнем уровне блока автоматически доступен в шаблоне: переменные, функции, импорты. Не нужно объявлять components, не нужно возвращать объект из setup().

Для пропсов используется defineProps(), для событий — defineEmits(), обе функции доступны без импорта. В TypeScript withDefaults() задаёт значения по умолчанию для типизированных пропсов.

Скилл срабатывает на файлах **/*.vue. Если пишете Vue 3 с Composition API — это стандартный синтаксис, который сокращает шаблонный код в два раза.

Какие задачи решает

  • писать Vue 3-компоненты с Composition API без лишнего return
  • автоматически регистрировать импортированные компоненты в шаблоне
  • объявлять пропсы и события через defineProps() и defineEmits()
  • задавать умолчания для типизированных пропсов через withDefaults()

Примеры запросов агенту

  • Переделай этот компонент на <script setup>
  • Создай форму в UserProfile.vue с <script setup>, пропсы username и avatar
  • Добавь обработчик клика, который эмитит событие close

Как установить script-setup

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill script-setup -a claude-code

2Вручную: положить файлы

~/.claude/skills/script-setup/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/script-setup/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о script-setup

Как установить script-setup в Claude Code?

Выполни npx skills add PatternsDev/skills --skill script-setup -a claude-code, скилл ляжет в ~/.claude/skills/script-setup/SKILL.md.

Что делает script-setup?

Учит агента писать Vue 3-компоненты с синтаксисом <script setup>: весь код на верхнем уровне доступен в шаблоне без явного return, импортированные компоненты регистрируются автоматически, пропсы и события объявляются через defineProps() и defineEmits().

Когда использовать script-setup?

Когда пишешь Vue 3-компоненты с Composition API. Это рекомендованный синтаксис для однофайловых компонентов, который убирает шаблонный код и делает определение компонента короче.

Исходный текст

SKILL.md · MIT
---
name: script-setup
description: Teaches Vue's script setup syntax for concise Composition API usage. Use when writing Vue 3 single-file components and you want a more ergonomic, less boilerplate syntax for the Composition API.
paths:
  - "**/*.vue"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "composables"
  - "components"
---

# `<script setup>`

## Table of Contents

- [When to Use](#when-to-use)
- [Instructions](#instructions)
- [Details](#details)
- [Source](#source)

`<script setup>` is compile-time syntactic sugar for using the Composition API in Vue single-file components. It eliminates boilerplate by automatically exposing top-level bindings to the template without an explicit `return` statement.

## When to Use

- Use this as the recommended syntax when using both SFCs and the Composition API in Vue 3
- This is helpful for reducing boilerplate in component definitions

## Instructions

- Add the `setup` attribute to the `<script>` tag: `<script setup>`
- Top-level bindings (variables, functions, imports) are automatically available in the template — no `return` needed
- Use `defineProps()` and `defineEmits()` (no import needed) for props and events
- Use `withDefaults()` to provide default prop values in TypeScript
- Imported components are automatically available in the template without explicit registration

## Details

Before we delve into the `<script setup>` syntax and what it is, let's quickly recap two concepts — **single-file components** and the **Composition API**.

In Vue, SFCs help couple logic by giving us the ability to define HTML/CSS and JS of a component all within a single **`.vue`** file. A single-file component consists of three parts:

```html
<template>
  <!-- HTML template goes here -->
</template>

<script>
  // JavaScript logic goes here
</script>

<style>
  /* CSS styles go here */
</style>
```

`<template>` contains the component's markup in plain HTML, `<script>` exports the component object constructor that consists of all the JS logic within that component, and `<style>` contains all the component styles.

The Composition API provides standalone functions representing Vue's core capabilities. These functions are primarily used within a single `setup()` option which serves as the entry point for utilizing the Composition API.

```html
<!-- Template -->

<script>
  export default {
    name: "MyComponent",
    setup() {
      // the setup function
    },
  };
</script>

<!-- Styles -->
```

> Be sure to read the [Composables](/vue/composables) guide for a deeper-dive into the advantages the Composition API provides over the traditional Options API syntax.

### `<script setup>`

`<script setup>` is compile-time syntactic sugar that allows for a more concise and efficient syntax in defining Vue options with the Composition API. According to the Vue documentation, it is the recommended syntax if one is using both SFCs and the Composition API.

By utilizing the `<script setup>` block, we can condense our component logic into a single block, eliminating the need for an explicit `setup()` function. To use the `<script setup>` syntax, we simply need to introduce the `setup` attribute to the `<script />` block.

```html
<script setup>
  // ...
</script>
```

Let's explore some of the main differences in syntax the `<script setup>` provides.

#### No return statement

With the `<script setup>` syntax, we no longer need to define a `return` statement at the end of our block. Bindings declared at the top level (functions, variables, imports, etc.) are readily accessible and usable in the template.

#### Before

```html
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Username: {{ state.username }}</p>
    <button @click="increment">Increment Count</button>
  </div>
</template>

<script>
  import { ref, reactive, onMounted } from "vue";

  setup() {
    const count = ref(0);
    const state = reactive({username: "John"});

    const increment = () => {
      count.value++;
    };

    onMounted(() => {
      console.log("Component mounted");
    });

    return {
      count,
      state,
      increment
    };
  },
</script>
```

#### After

```html
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Username: {{ state.username }}</p>
    <button @click="increment">Increment Count</button>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from "vue";

  const count = ref(0);
  const state = reactive({ username: "John" });

  const increment = () => {
    count.value++;
  };

  onMounted(() => {
    console.log("Component mounted");
  });
</script>
```

#### No locally registered components

Component imports are automatically recognized and resolved within the `<script setup>` block without the need to explicitly declare the component within a `components` option.

#### Before

```html
<template>
  <ButtonComponent />
</template>

<script>
  import ButtonComponent from "./components/ButtonComponent.vue";

  export default {
    setup() {
      // the setup function
    },
    components: {
      ButtonComponent,
    },
  };
</script>
```

#### After

```html
<template>
  <ButtonComponent />
</template>

<script setup>
  import { ButtonComponent } from "./components/Button";
</script>
```

#### `defineProps()`

Props can be accessed directly within the `<script setup>` block by using the `defineProps()` function.

#### Before

```html
<template>
  <button>{{ buttonText }}</button>
</template>

<script>
  export default {
    props: {
      buttonText: String,
    },
  };
</script>
```

#### After

```html
<template>
  <button>{{ buttonText }}</button>
</template>

<script setup>
  const { buttonText } = defineProps({
    buttonText: String,
  });
</script>
```

`defineProps()` also allows us to declare the shape of our props with pure TypeScript.

```html
<template>
  <button>{{ buttonText }}</button>
</template>

<script setup lang="ts">
  const { buttonText } = defineProps<{ buttonText: string }>();
</script>
```

To provide default prop values in the type-only declaration we have above, we can use the `withDefaults()` compiler macro to achieve this.

```html
<template>
  <button>{{ buttonText }}</button>
</template>

<script setup lang="ts">
  const { buttonText } = withDefaults(defineProps<{ buttonText: string }>(), {
    buttonText: "Initial button text",
  });
</script>
```

`defineProps` is available only in `<script setup>` and can be used without having to be imported.

#### `defineEmits()`

Similar to props, custom events can be emitted directly within the `<script setup>` block by using the `defineEmits()` function in a component.

#### Before

```html
<template>
  <button @click="closeButton">Button Text</button>
</template>

<script>
  export default {
    emits: ["close"],
    setup(props, { emit }) {
      const closeButton = () => emit("close");

      return {
        closeButton,
      };
    },
  };
</script>
```

#### After

```html
<template>
  <button @click="closeButton">Button Text</button>
</template>

<script setup>
  const emit = defineEmits(["close"]);
  const closeButton = () => emit("close");
</script>
```

Like `defineProps`, `defineEmits` is a special keyword available only in `<script setup>` and can also be used without having to be imported. It also allows us to pass in types directly when working within a TypeScript setting.

```html
<template>
  <button @click="closeButton">Button Text</button>
</template>

<script setup lang="ts">
  const emit = defineEmits<{ (e: "close"): void }>(["close"]);
  const closeButton = () => emit("close");
</script>
```

### `<script setup>` vs. `setup()`

For larger components that have a large number of returned options and many locally registered child components, the `<script setup>` syntax helps remove a lot of boilerplate code which leads to cleaner and more focused component definitions that subsequently helps make the codebase more readable and maintainable.

Outside of reducing boilerplate, the `<script setup>` syntax also provides better runtime performance, better IDE-type inference performance, and the ability to declare the shape of props and emitted events with TypeScript.

For a full list of changes that need to be kept in mind when working with the `<script setup>` syntax, refer to the official Vue documentation shared below.

## Source

- [patterns.dev/vue/script-setup](https://patterns.dev/vue/script-setup)

### References

- [`<script setup>` | Vue Documentation](https://vuejs.org/api/sfc-script-setup.html)

© patterns.dev · MIT · PatternsDev/skills

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
vue-best-practices github.com/vuejs-ai Скилл vue-best-practices задаёт стандарты разработки на Vue 3 с Composition API и TypeScript. Пригодится при написании SFC-компонентов, composables и настройке реактивности. CX Codex +1 45 800установок vue Anthony Fu Скилл vue для Claude Code помогает писать компоненты Vue 3 и разбирать Composition API. Он подключается при работе с SFC, макросами defineProps и defineEmits, наблюдателями и встроенными компонентами. CX Codex +1 36 900установок vue-development travisjneuman Скилл vue-development для Claude Code помогает писать код на Vue 3 с синтаксисом Composition API и Script Setup. Подключается при настройке Pinia, создании композаблов и разработке на Nuxt 3. CX Codex +1 143установок vue-expert https://github.com/Jeffallan Скилл vue-expert для Claude Code пишет код на Vue 3 с Composition API, настраивает Nuxt 3, Pinia и Vite. Создаёт компоненты, PWA и гибридные приложения. CX Codex +1 4 800установок vue3-composition-api-cursorrules-prompt-file PatrickJS Правило vue3-composition-api-cursorrules-prompt-file задаёт рекомендации для разработки на Vue 3 с Composition API: от реактивного состояния до структуры проекта. Пригодится, чтобы Cursor учитывал эти практики при работе с файлами. CX Codex +1 ★ 41 178звёзд репо vue-skilld skilld-dev Скилл vue-skilld помогает писать компоненты и композаблы на Vue 3.6. Направляет агента при переходе на Vapor Mode, настройке SSR и обновлении кода с версий 3.4–3.5. CX Codex +1 434установок

Из того же набора58

Весь набор →
async-components Скилл async-components учит агента загружать Vue-компоненты асинхронно через defineAsyncComponent(), чтобы не тянуть тяжёлые модалки и диалоги при старте. CX Codex +1 207установок container-presentational Скилл container-presentational учит разделять Vue-компоненты на контейнеры (логика, запросы) и презентационные (вёрстка). Презентационный компонент получает данные через props и не трогает состояние. CX Codex +1 205установок data-provider Объясняет паттерн data provider во Vue: логика загрузки и состояния передаётся дочерним компонентам через scoped slots. CX Codex +1 204установок state-management Скилл state-management направляет агента при проектировании реактивного состояния во Vue 3. Помогает выбрать между props, простым хранилищем на reactive() и Pinia. CX Codex +1 201установок dynamic-components Скилл dynamic-components для Claude Code переключает компоненты Vue через <component :is> и сохраняет их состояние с <KeepAlive>. Переключает вкладки и панели без роутера. CX Codex +1 198установок provide-inject Скилл provide-inject учит агента использовать provide() и inject() из Vue для передачи данных глубоко вложенным компонентам без прокидывания пропсов через каждый уровень. CX Codex +1 196установок render-functions Скилл render-functions учит ИИ-агента писать рендер-функции через h() и синтаксис JSX во Vue. Пригодится при сборке UI-библиотек и динамической разметки, где возможностей шаблонов не хватает. CX Codex +1 196установок renderless-components Скилл renderless-components учит паттерну renderless-компонентов во Vue: логика отдельно, разметка — на вызывающий код через scoped slots. CX Codex +1 194установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой