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

container-presentational — скилл для Claude Code: что делает

Скилл container-presentational учит разделять Vue-компоненты на контейнеры (логика, запросы) и презентационные (вёрстка). Презентационный компонент получает данные через props и не трогает состояние.

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

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

Что делает container-presentational

Скилл обучает паттерну container/presentational для Vue 3: контейнер забирает данные из API и передаёт их презентационному компоненту, который только рендерит. Презентационный компонент не знает, откуда пришли данные, и не меняет их — получает через props и отдаёт в шаблон. Контейнер держит ref, вызывает fetch в onMounted и прокидывает результат вниз.

Скилл показывает современную альтернативу — composable useDogImages(), который инкапсулирует логику запроса без обёртки-контейнера. Презентационный компонент вызывает composable напрямую и получает реактивный массив. Без Composition API или хуков контейнер был обязателен; с ними он опционален, но разделение логики и вида остаётся полезным для переиспользования и тестирования.

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

  • разделить логику запросов и рендеринг во Vue-компонентах
  • сделать презентационный компонент переиспользуемым без привязки к API
  • заменить контейнер-обёртку на composable с useDogImages()
  • протестировать вёрстку независимо от источника данных

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

  • Создай презентационный компонент DogImages.vue, который принимает массив dogs через props и рендерит картинки
  • Вынеси запрос собачьих фото в composable useDogImages() и используй его в компоненте
  • Перепиши контейнер DogImagesContainer.vue на composable с onMounted и fetch

Как установить container-presentational

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill container-presentational -a claude-code

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

~/.claude/skills/container-presentational/SKILL.md

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

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

Вопросы о container-presentational

Как установить container-presentational в Claude Code?

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

Что делает скилл container-presentational?

Учит разделять Vue-компоненты на контейнеры, которые забирают данные, и презентационные, которые только рендерят через props. Показывает, как заменить контейнер на composable.

Зачем нужен паттерн container/presentational?

Презентационный компонент не зависит от источника данных — его легко переиспользовать и тестировать. С Composition API контейнер можно заменить на composable, который даёт то же разделение без лишнего слоя.

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

SKILL.md · MIT
---
name: container-presentational
description: Teaches the container/presentational pattern for Vue components. Use when you want to separate data fetching and business logic from presentation for better testability and reuse.
paths:
  - "**/*.vue"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "composables"
  - "components"
---

# Container/Presentational Pattern

## Table of Contents

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

In 2015, Dan Abramov wrote an article titled ["Presentational and Container Components"](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0) that changed the way many developers thought about component architecture in React. He introduced a pattern that separated components into two categories:

1. **Presentational Components (or Dumb Components)**: These are concerned with how things look. They don't specify how the data is loaded or mutated but rather receive data and callbacks exclusively via props.
2. **Container Components (or Smart Components)**: These are concerned with how things work. They provide the data and behavior to presentational or other container components.

## When to Use

- Use this when you want a clear separation between data-fetching logic and UI rendering
- This is helpful for making presentational components reusable and easy to test

## Instructions

- Container components handle data fetching and state; presentational components handle rendering via props
- Prefer composables over container components in Vue 3 for the same separation of concerns
- Keep presentational components stateless — they receive data only through props
- Use the `useDogImages()` composable pattern as a modern alternative to container wrappers

## Details

While this pattern was mainly associated with React, its fundamental principle was adopted and adapted in various forms across other libraries and frameworks.

Dan's distinction offered a clearer and more scalable way to structure JavaScript applications. By clearly defining the responsibilities of different types of components, developers could ensure better reusability of the UI components (presentational) and logic (containers).

However, with the emergence of hooks in React and the Composition API in Vue 3, the clear boundary between presentational and container components began to blur. Hooks and the Composition API began allowing developers to encapsulate and reuse state and logic without necessarily being confined to a class-based container component or the Options API. With that being said, the pattern can still be helpful at certain times.

Let's say we want to create an application that fetches 6 dog images, and renders these images on the screen.

To follow the container/presentational pattern, we want to enforce the separation of concerns by separating this process into two parts:

1. **Presentational Components**: Components that care about _**how**_ data is shown to the user. In this example, that's the rendering of the list of dog images.
2. **Container Components**: Components that care about _**what**_ data is shown to the user. In this example, that's fetching the dog images.

Fetching the dog images deals with **application logic**, whereas displaying the images only deals with the **view**.

### Presentational Component

A presentational component receives its data through `props`. Its primary function is to simply **display the data it receives** the way we want them to, including styles, _without modifying_ that data.

When rendering the dog images, we simply want to map over each dog image that was fetched from the API, and render those images. We can create a `DogImages` component that receives the data through `props`, and renders the data it received.

```html
<template>
  <div>
    <div v-for="(dog, index) in dogs" :key="index">
      <img :src="dog" alt="Dog" />
    </div>
  </div>
</template>

<script setup>
  defineProps(["dogs"]);
</script>
```

The `DogImages` component is a presentational component. Presentational components are _usually_ stateless: they do not contain their own Vue state, unless they need a state for UI purposes. Presentational components receive their data from **container components**.


### Container Component

The primary function of container components is to **pass data** to presentational components, which they _contain_. Container components themselves usually don't render any other components besides the presentational components that care about their data. Since they don't render anything themselves, they usually do not contain any styling either.

We need to create a **container component** that fetches this data, and passes this data to the presentational component `DogImages` in order to display it on the screen.

```html
<template>
  <DogImages :dogs="dogs" />
</template>

<script setup>
  import { ref, onMounted } from "vue";
  import DogImages from "./DogImages.vue";

  const dogs = ref([]);

  onMounted(async () => {
    const response = await fetch(
      "https://dog.ceo/api/breed/labrador/images/random/6"
    );
    const { message } = await response.json();
    dogs.value = message;
  });
</script>
```

Combining these two components together makes it possible to separate handling application logic with the view.

### Composables

In many cases, the Container/Presentational pattern can be replaced with composables. The introduction of the Composition API made it easy for developers to add statefulness without needing a container component to provide that state.

Instead of having the data fetching logic in a container component, we can create a custom composable that fetches the images, and returns the array of dogs.

```js
import { ref, onMounted } from "vue";

export function useDogImages() {
  const dogs = ref([]);

  onMounted(async () => {
    const response = await fetch(
      "https://dog.ceo/api/breed/labrador/images/random/6"
    );
    const { message } = await response.json();
    dogs.value = message;
  });

  return { dogs };
}
```

By using this composable, we no longer need the wrapping container component to fetch the data. Instead, we can use this composable directly in our presentational `DogImages` component!

```html
<template>
  <div>
    <div v-for="(dog, index) in dogs" :key="index">
      <img :src="dog" alt="Dog" />
    </div>
  </div>
</template>

<script setup>
  import { useDogImages } from "../composables/useDogImages";

  const { dogs } = useDogImages();
</script>
```

By using the `useDogImages` composable, we still separated the application logic from the view. We're simply using the returned data from the composable, without modifying that data within the component.

Composables make it easy to separate logic and view in a component, just like the Container/Presentational pattern. It saves us the extra layer that was necessary in order to wrap the presentational component within the container component.

## Source

- [patterns.dev/vue/container-presentational](https://patterns.dev/vue/container-presentational)

### References

- [Presentational and Container Components - Dan Abramov](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0)
- [Composables | Vue Documentation](https://vuejs.org/guide/reusability/composables.html)

© patterns.dev · MIT · PatternsDev/skills

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

Все скиллы по теме «Фронтенд и UI» →
vuetify0 vuetifyjs Скилл vuetify0 подсказывает агенту, какие компоненты и composables из @vuetify/v0 взять вместо самописной логики — от кнопки до виртуального списка. CX Codex +1 742установок vueuse-functions SerKo Скилл vueuse-functions подбирает функции VueUse для задач во Vue.js и Nuxt и помогает применять их вместо собственного кода. Подходит для Vue 3+ и Nuxt 3+. CX Codex +1 4 100установок nuxt-data Claude Skills Maintainers Скилл nuxt-data для работы с данными в Nuxt 4: композаблы, useFetch и useAsyncData, состояние через useState и Pinia. CX Codex +1 408установок vueuse-core-skilld skilld-dev Скилл vueuse-core-skilld с полным API @vueuse/core 15.0.0: новые composables, правила миграции с v14, устаревшие функции и требования окружения. CX Codex +1 219установок vueuse-math-skilld skilld-dev Скилл vueuse-math-skilld для работы с композаблами @vueuse/math в Vue 3: клампинг, проекция, округление, агрегация реактивных чисел. CX Codex +1 119установок ui-design-patterns manutej Скилл ui-design-patterns для Claude Code — справочник по паттернам навигации, форм, вывода данных, обратной связи и доступности. Помогает выбрать паттерн или проверить существующий интерфейс. CX Codex +1 854установок

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

Весь набор →
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установок async-components Скилл async-components учит агента загружать Vue-компоненты асинхронно через defineAsyncComponent(), чтобы не тянуть тяжёлые модалки и диалоги при старте. CX Codex +1 207установок 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установок

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

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