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

async-components — скилл для Claude Code: Vue-компоненты по запросу

Скилл async-components учит агента загружать Vue-компоненты асинхронно через defineAsyncComponent(), чтобы не тянуть тяжёлые модалки и диалоги при старте.

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

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

Что делает async-components

Скилл показывает, как разбивать бандл Vue-приложения: тяжёлые компоненты загружаются по требованию, а не сразу со всем кодом страницы. Агент оборачивает импорт в defineAsyncComponent(() => import('./Modal.vue')) и связывает его с v-if, чтобы запрос ушёл только когда компонент нужен.

Внутри — правила для .vue файлов, примеры с loadingComponent и errorComponent (заглушка на время загрузки и обработка ошибок), настройки delay и timeout. Если компонент маленький или всегда виден на старте, выигрыша не будет: скилл объясняет агенту, когда такой подход вреден.

Зависимостей кроме Vue нет. Скилл работает во всех платформах из списка, устанавливается через npx skills add с флагом адаптера.

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

  • разбить бандл Vue-приложения на чанки
  • отложить загрузку модального окна до клика
  • показать заглушку пока асинхронный компонент грузится
  • обработать ошибку загрузки компонента

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

  • Оберни импорт Modal.vue в defineAsyncComponent, чтобы он грузился только при рендере
  • Добавь loadingComponent в опции defineAsyncComponent для AsyncModal.js
  • Покажи как связать v-if с асинхронным компонентом, чтобы запрос ушёл по клику

Как установить async-components

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill async-components -a claude-code

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

~/.claude/skills/async-components/SKILL.md

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

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

Вопросы об async-components

Как установить async-components в Claude Code?

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

Что делает async-components?

Учит агента загружать Vue-компоненты по требованию через defineAsyncComponent(), чтобы не тащить весь код при старте страницы.

Когда async-components не подходит?

Для маленьких компонентов, где накладные расходы на запрос чанка больше экономии, и для компонентов, которые всегда видны при загрузке — асинхронность только задержит их появление.

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

SKILL.md · MIT
---
name: async-components
description: Teaches async component loading in Vue for performance optimization. Use when you have heavy components that aren't needed on initial render and can be loaded on demand.
paths:
  - "**/*.vue"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "composables"
  - "components"
---

# Async Components

## Table of Contents

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

When developing large web applications, performance is paramount. The speed with which a page loads and the responsiveness of its interactive elements can greatly impact user experience. As web applications grow in size and complexity, it can become important to ensure that large bundles of code are loaded only when needed. Enter asynchronous components in Vue.

Components are the fundamental building blocks for constructing the UI. Typically, when we use components, they're automatically loaded and parsed, even if they aren't immediately needed.

## When to Use

- Use this when components have large bundle sizes and aren't needed on initial page load
- This is helpful for modals, dialogs, or any UI that is conditionally rendered based on user action

## When NOT to Use

- For small components where the async loading overhead (chunk request, parsing) outweighs the bundle savings
- For components that are always visible on initial render — async loading delays their appearance
- When the component is already part of the main chunk and splitting it out wouldn't meaningfully reduce bundle size

## Instructions

- Use `defineAsyncComponent()` with dynamic `import()` to load components on demand
- Provide `loadingComponent` and `errorComponent` options for better user experience
- Combine with `v-if` to trigger async loading only when the component is actually needed
- Use the `delay` and `timeout` options for fine-grained control over loading behavior

## Details

Asynchronous components, on the other hand, allow us to define components in a way that they're loaded and parsed only when they're required or when certain conditions are met.

Assume we had a simple modal component that becomes rendered when a button is clicked from the parent. The `Modal.vue` component file will only contain template and styles that dictate how the modal appears.

```html
<template>
  <div class="modal-mask">
    <div class="modal-container">
      <div class="modal-body">
        <h3>This is the modal!</h3>
      </div>

      <div class="modal-footer">
        <button class="modal-default-button" @click="$emit('close')">OK</button>
      </div>
    </div>
  </div>
</template>
```

In the parent `App` component, we can render the modal component and a button that when clicked toggles the visibility of the modal component with the help of a reactive boolean value (`showModal`).

```html
<template>
  <button id="show-modal" @click="showModal = true">Show Modal</button>
  <Modal v-if="showModal" :show="showModal" @close="showModal = false" />
</template>

<script setup>
  import { ref } from "vue";
  import Modal from "./components/Modal.vue";

  const showModal = ref(false);
</script>
```

From this example, we can see that the modal component is shown only under a specific circumstance — when the user clicks the `Show Modal` button. Despite this, the JavaScript bundle associated with the component **is loaded automatically when the entire webpage is loaded** even before the modal is made visible.

This is fine for the majority of cases. However, under conditions where the bundle size of the modal is really large and/or the application has a multitude of such components, this can lead to a delayed initial load time. With every added bundle, even if it's related to components that are rarely used, the time it takes for the initial page to load grows.

### defineAsyncComponent

This is where Vue allows us to divide an app into smaller chunks by loading components asynchronously with the help of the [`defineAsyncComponent()`](https://vuejs.org/api/general.html#defineasynccomponent) function.

```js
import { defineAsyncComponent } from "vue";

const AsyncComp = defineAsyncComponent(() => {
  return new Promise((resolve, reject) => {
    // ...load component from the server
    resolve(/* loaded component */);
  });
});
```

The `defineAsyncComponent()` function accepts a loader function that returns a Promise that resolves to the imported component. However, instead of defining our async component function like the above, we can leverage [dynamic imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) to load an ECMAScript module asynchronously.

```js
import { defineAsyncComponent } from "vue";

export const AsyncComp = defineAsyncComponent(() =>
  import("./components/MyComponent.vue")
);
```

Let's see this in action for our modal example. We'll create a new file titled `AsyncModal.js`:

```js
import { defineAsyncComponent } from "vue";

export const AsyncModal = defineAsyncComponent(() => import("./Modal.vue"));
```

In our parent `App` component, we'll now import and use the `AsyncModal` asynchronous component in place of the `Modal` component.

```html
<template>
  <button id="show-modal" @click="showModal = true">Show Modal</button>
  <AsyncModal v-if="showModal" :show="showModal" @close="showModal = false" />
</template>

<script setup>
  import { ref } from "vue";
  import { AsyncModal } from "./components/AsyncModal";

  const showModal = ref(false);
</script>
```

With this small change, our modal component will now be asynchronously loaded! When our application webpage initially loads, the bundle for the `Modal` component _is no longer loaded automatically upon page load_. When we click the button to trigger the modal to be shown, the bundle is then asynchronously loaded as the modal component is being rendered.

### Loading and error UI

With `defineAsyncComponent()`, Vue provides developers with more than just a means of asynchronously loading components. It also offers capabilities to display feedback to users during the loading process and handle any potential errors.

#### loadingComponent

There may be times we may want to provide visual feedback to users while a component is being fetched. To achieve this, `defineAsyncComponent()` has a `loadingComponent` option that lets us specify a component to show during the loading phase.

```js
import { defineAsyncComponent } from "vue";
import Loading from "./Loading.vue";

export const AsyncModal = defineAsyncComponent({
  loader: () => import("./Modal.vue"),
  loadingComponent: Loading,
});
```

As the modal component becomes asynchronously loaded, the user will now be presented with a `Loading...` message.

#### errorComponent

In certain conditions (e.g. poor internet connections), there may be chances that the asynchronous component fails to load. The `defineAsyncComponent()` function offers the `errorComponent` option to handle such situations, allowing us to specify a component to be displayed when there's a loading error.

```js
import { defineAsyncComponent } from "vue";
import Loading from "./Loading.vue";
import Error from "./Error.vue";

export const AsyncModal = defineAsyncComponent({
  loader: () => import("./Modal.vue"),
  loadingComponent: Loading,
  errorComponent: Error,
});
```

When the modal component fails to load, the `Error` component template will be shown.

The `defineAsyncComponent()` function accepts further options like `delay`, `timeout`, `suspensible`, and `onError()` which provide developers with more granular control over the asynchronous loading behavior and user experience. Be sure to check out the [API documentation](https://vuejs.org/api/general.html#defineasynccomponent) for more details on these properties.

The `defineAsyncComponent()` function can help in breaking down the initial load of a Vue application into manageable chunks by deferring the loading of certain components until they're needed. This can help improve page load times and overall application performance especially when an application has numerous components that have a large bundle size.

## Source

- [patterns.dev/vue/async-components](https://patterns.dev/vue/async-components)

### References

- [Async Components | Vue Documentation](https://vuejs.org/guide/components/async.html#async-components)

© patterns.dev · MIT · PatternsDev/skills

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

Все скиллы по теме «Фронтенд и UI» →
async-defer-await tech-leads-club Правило async-defer-await учит откладывать операции await только на те ветки кода, где они действительно нужны. Это избегает блокировки путей выполнения, которые могут вернуться раньше. CX Codex +1 ★ 7 191звёзд репо csharp-async официальный github Скилл csharp-async для GitHub Copilot, который проверяет асинхронный код на C# и подсказывает, как привести его к принятым практикам. Включается при ревью и написании методов с Task и await. CX Codex +1 10 883установок vueuse-components-skilld skilld-dev Скилл vueuse-components-skilld помогает писать и отлаживать Vue 3-шаблоны с компонентами и директивами @vueuse/components. Пригодится и при переходе от composable к компонентной или директивной форме. CX Codex +1 168установок rust-async-patterns Seth Hobson Скилл rust-async-patterns для Claude Code помогает писать и разбирать асинхронный Rust на Tokio: задачи, каналы, потоки и обработку ошибок. Помогает создавать сетевые сервисы и отлаживать код. CX Codex +1 20 625установок unit-test-scheduled-async giuseppe-trisciuoglio Скилл unit-test-scheduled-async с готовыми шаблонами юнит-тестов для Spring-методов @Scheduled и @Async: JUnit 5, CompletableFuture, Awaitility, Mockito. CX Codex +1 3 900установок ue-async-threading quodsoler Скилл ue-async-threading помогает выносить вычисления из игрового потока Unreal Engine 5.8, настраивать параллельные циклы и возвращать данные в Game Thread. CX Codex +1 1 300установок

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

Весь набор →
flyweight-pattern Скилл flyweight-pattern учит агента применять паттерн приспособленец для экономии памяти при создании множества похожих объектов. CX Codex +1 634установок mediator-pattern Скилл mediator-pattern для Claude Code объясняет паттерн «посредник»: компоненты общаются через одну точку, а не напрямую. Снижает число прямых связей между объектами. CX Codex +1 631установок components Скилл components для Claude Code помогает собирать Vue-интерфейсы из однофайловых компонентов, связывая шаблон, логику и стили. Помогает структурировать экран и повторно использовать его части. CX Codex +1 212установок composables Скилл composables для Claude Code учит писать Vue-композаблы — переиспользуемую логику на Composition API. Выносит реактивное состояние, вычисления и побочные эффекты в функции для нескольких компонентов. CX Codex +1 211установок 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установок

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

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