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

dynamic-components — скилл для Claude Code: компоненты Vue

Скилл dynamic-components для Claude Code переключает компоненты Vue через <component :is> и сохраняет их состояние с <KeepAlive>. Переключает вкладки и панели без роутера.

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

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

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

Скилл разбирает приём с зарезервированным элементом <component>: атрибут is привязывается к реактивному значению, и Vue монтирует нужный компонент вместо цепочки v-if/v-else. В примере три компонента — Home, Feed и History — собраны в объект tabs, где лежат сами определения компонентов.

При переключении компонент по умолчанию размонтируется и теряет своё состояние. В скилле есть шаг с <KeepAlive>: обёртка вокруг <component> сохраняет данные, поэтому счётчик во вкладке не сбрасывается при возврате.

Срабатывает он на файлах **/*.vue — в проекте без однофайловых компонентов Vue ждать его нечего. Рядом в наборе идут скиллы composables и components.

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

  • Переключить вкладки без роутера и лишних маршрутов
  • Убрать лесенку из v-if/v-else в шаблоне App.vue
  • Сохранить введённые данные при переходе между вкладками
  • Связать имя вкладки с импортированным компонентом

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

  • Сделай переключение вкладок Home, Feed и History через <component :is>, без роутера.
  • Оберни <component> в <KeepAlive>, чтобы счётчик не сбрасывался при возврате на вкладку.
  • Замени цепочку v-if/v-else в App.vue на динамический компонент.

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

1Через Skills CLI (Vercel)

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

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

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

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

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

Вопросы о dynamic-components

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

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

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

Показывает, как выводить разные компоненты Vue из одного тега <component>, привязывая к нему is, и как сохранять их состояние с <KeepAlive>.

Чем это лучше цепочки v-if/v-else?

Шаблон не разрастается с каждой новой вкладкой: выбор идёт по одному реактивному значению, а компоненты просто лежат в объекте.

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

SKILL.md · MIT
---
name: dynamic-components
description: Teaches dynamic component switching with Vue's <component> element. Use when you need to render different components conditionally based on runtime state using the is attribute.
paths:
  - "**/*.vue"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "composables"
  - "components"
---

# Dynamic Components

## Table of Contents

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

Dynamic components constitute the ability to dynamically change (i.e. switch) between components by binding an `is` attribute to the reserved `<component>` element.

We'll go through an example to best understand how dynamic components work. Assume we have separate components titled `Home`, `Feed`, and `History` that simply display text dictating what component it is.

## When to Use

- Use this when you need to render different components based on user interaction (e.g., tabs, views)
- This is helpful as an alternative to multiple `v-if`/`v-else` blocks for conditional component rendering

## Instructions

- Bind the `is` attribute on `<component>` to a reactive value referencing the component definition
- Use a `tabs` object mapping names to imported component definitions
- Wrap `<component>` with `<KeepAlive>` to preserve state when switching between dynamic components

## Details

```html
<!-- Home -->
<template><div class="tab">Home component</div></template>

<!-- Feed -->
<template><div class="tab">Feed component</div></template>

<!-- History -->
<template><div class="tab">History component</div></template>
```

Our goal is to build an interface that surfaces a list of tabs that can be clicked. Depending on what tab is clicked, we want to dynamically render a certain component.

When clicking between the tabs, we want components to be dynamically unmounted and mounted without the use of routing. Though something like this could be achieved by conditionally rendering child templates with the help of directives like [`v-if` and `v-else`](https://vuejs.org/guide/essentials/conditional.html), this is a perfect use case of Vue dynamic components.

In the parent `App` component of our app, we can first import the three individual components to have them available in the template. We'll also create a `currentTab` reactive property that is given an initial value of `"Home"`.

```html
<script setup>
  import { ref } from "vue";
  import Home from "./components/Home.vue";
  import Feed from "./components/Feed.vue";
  import History from "./components/History.vue";

  const currentTab = ref("Home");
  const tabs = {
    Home,
    Feed,
    History,
  };
</script>
```

Note that our `tabs` object references the actual component definitions and not just the component names.

In the `App` component template, we'll look to render three separate tab buttons — one for each component we intend to display. We'll use the [`v-for` directive](https://vuejs.org/api/built-in-directives.html#v-for) to help achieve this.

```html
<template>
  <div class="demo">
    <button
      v-for="(_, tab) in tabs"
      :key="tab"
      :class="['tab-button', { active: currentTab === tab }]"
      @click="currentTab = tab"
    >
      {{ tab }}
    </button>
  </div>
</template>
```

To dynamically render a certain child component, we'll bind an `is` attribute to the reserved `<component>` element. The value attached to the `is` attribute should correspond to the child component that we want to render dynamically.

```html
<template>
  <div class="demo">
    <button
      v-for="(_, tab) in tabs"
      :key="tab"
      :class="['tab-button', { active: currentTab === tab }]"
      @click="currentTab = tab"
    >
      {{ tab }}
    </button>
    <component :is="tabs[currentTab]" class="tab"></component>
  </div>
</template>

<script setup>
  import { ref } from "vue";
  import Home from "./components/Home.vue";
  import Feed from "./components/Feed.vue";
  import History from "./components/History.vue";

  const currentTab = ref("Home");

  const tabs = {
    Home,
    Feed,
    History,
  };
</script>
```

With the dynamic `<component />` element placed in our template, the child components are now dynamically unmounted and mounted depending on which tab has been selected.

### Preserving state

Preserving state can be an important consideration to keep in mind when using dynamic components. By default, when a component is unmounted, its state is lost. However, Vue provides a way to preserve the state of dynamic components using the `<KeepAlive>` component.

To preserve the state of dynamic components, we can wrap the `<component>` element with the `<KeepAlive>` component.

```html
<template>
  <div class="demo">
    <!--  -->
    <KeepAlive>
      <component :is="tabs[currentTab]" class="tab"></component>
    </KeepAlive>
  </div>
</template>

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

With the `<KeepAlive>` component wrapping the `<component>` element, the state of the dynamic components will be preserved when they are unmounted. This means that any data or component state will be maintained, and the component will retain its previous state when it is mounted again.

To see an example of this, we can update each of our child components to contain a simple counter that increments.

```html
<!-- Repeat this counter example for Home, Feed, and History -->
<template>
  <div class="tab">
    Home component
    <p>Counter: {{ counter }}</p>
    <button @click="incrementCounter">Increment</button>
  </div>
</template>

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

  const counter = ref(0);

  const incrementCounter = () => {
    counter.value++;
  };
</script>
```

With these changes, the counter state for each respective child component is kept preserved even as we dynamically switch between components.

By using the `<KeepAlive>` component, we can enhance the behavior of dynamic components by preserving their state and providing a smoother user experience when switching between tabs.

## Source

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

### References

- [Dynamic Components | Vue Documentation](https://vuejs.org/guide/essentials/component-basics.html#dynamic-components)
- [KeepAlive | Vue Documentation](https://vuejs.org/guide/built-ins/keep-alive.html)

© patterns.dev · MIT · PatternsDev/skills

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

Все скиллы по теме «Фронтенд и UI» →
vueuse-components-skilld skilld-dev Скилл vueuse-components-skilld помогает писать и отлаживать Vue 3-шаблоны с компонентами и директивами @vueuse/components. Пригодится и при переходе от composable к компонентной или директивной форме. CX Codex +1 168установок interaction-patterns-components hueyexe Скилл interaction-patterns-components помогает агенту выбирать и критиковать UI-паттерны и переиспользуемые компоненты: навигация, таблицы, модалки, формы, состояния. CX Codex +1 622установок Open Components uxfront-com MCP-сервер Open Components отдаёт агенту контракты и правила UI-компонентов по разделам, чтобы код соответствовал стандарту UX, DX и AX. Подключается без входа в аккаунт. CX Codex +1 ★ 16звёзд репо vuetify0 vuetifyjs Скилл vuetify0 подсказывает агенту, какие компоненты и composables из @vuetify/v0 взять вместо самописной логики — от кнопки до виртуального списка. CX Codex +1 742установок vuejs-development manutej Скилл vuejs-development для Claude Code и других ИИ-агентов: покрывает реактивность, Composition API, однофайловые компоненты и директивы Vue 3. Помогает писать SPA и переходить с Options API. CX Codex +1 512установок building-components vercel Скилл building-components помогает проектировать доступные UI-компоненты, их API, темы и документацию. CX Codex +1 15 400установок

Из того же набора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установок provide-inject Скилл provide-inject учит агента использовать provide() и inject() из Vue для передачи данных глубоко вложенным компонентам без прокидывания пропсов через каждый уровень. CX Codex +1 196установок render-functions Скилл render-functions учит ИИ-агента писать рендер-функции через h() и синтаксис JSX во Vue. Пригодится при сборке UI-библиотек и динамической разметки, где возможностей шаблонов не хватает. CX Codex +1 196установок script-setup Учит агента писать Vue 3-компоненты с <script setup> — без лишнего кода и явного return. CX Codex +1 195установок renderless-components Скилл renderless-components учит паттерну renderless-компонентов во Vue: логика отдельно, разметка — на вызывающий код через scoped slots. CX Codex +1 194установок

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

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