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

data-provider — скилл для Claude Code: установка

Объясняет паттерн data provider во Vue: логика загрузки и состояния передаётся дочерним компонентам через scoped slots.

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

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

Что делает data-provider

Скилл показывает, как вынести получение данных и управление состоянием в renderless-компонент. Его шаблон содержит один <slot>, а через scoped slot props наружу передаются данные, состояние загрузки и методы действий. Родитель получает их через v-slot и передаёт в компонент представления.

В примере используются DataProvider.vue и JokeCard.vue: первый загружает данные, второй отвечает за отображение. Такой подход подходит, когда несколько компонентов используют одни данные, но показывают их по-разному. Файлы Vue подходят под область **/*.vue.

В Vue 3+ лишний слой компонента усложнит шаблон, когда composable уже справляется. Для установки нужен npx или gh в зависимости от платформы.

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

  • вынести загрузку данных из компонента интерфейса
  • передать состояние загрузки через scoped slots
  • разделить логику данных и отображение
  • дать нескольким компонентам общий источник данных

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

  • Разбери этот компонент Vue и вынеси загрузку данных в DataProvider.vue.
  • Покажи, как передать data, loading и fetchJoke в JokeCard.vue через v-slot.
  • Проверь, нужен ли здесь data provider или достаточно composable в Vue 3+.

Как установить data-provider

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill data-provider -a claude-code

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

~/.claude/skills/data-provider/SKILL.md

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

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

Вопросы о data-provider

Как установить data-provider в Claude Code?

Выполните npx skills add PatternsDev/skills --skill data-provider -a claude-code, затем проверьте файл ~/.claude/skills/data-provider/SKILL.md.

Что делает data-provider?

Скилл объясняет паттерн, где renderless-компонент управляет данными и состоянием, а дочерний компонент получает их через scoped slots и занимается представлением.

Когда data-provider не нужен во Vue?

Если данные использует один компонент или composable уже решает задачу, дополнительный слой data provider добавит лишнюю косвенность. В Vue 3+ скилл советует рассмотреть composable.

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

SKILL.md · MIT
---
name: data-provider
description: Teaches the data provider pattern using renderless components and scoped slots. Use when you need to abstract data fetching or state management logic and expose it to child components via slots.
paths:
  - "**/*.vue"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "composables"
  - "components"
---

# Data Provider Pattern

## Table of Contents

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

In a previous article, we've come to learn how renderless components help separate the logic of a component from its presentation. This becomes useful when we need to create reusable logic that can be applied to different UI implementations.

Renderless components also allow us to leverage another helpful pattern known as the **data provider pattern**.

## When to Use

- Use this when multiple components need to consume the same data but display it differently
- This is helpful for centralizing data-fetching logic without coupling it to specific UI components

## When NOT to Use

- When composables can handle the data logic without the extra component layer (Vue 3+)
- When only one component consumes the data — a composable or inline fetch is simpler
- When the data-provider nesting adds indirection that makes the template harder to follow

## Instructions

- Create a data provider component whose template is a single `<slot>` with scoped slot props
- Pass data, loading state, and action methods as scoped slot props to child components
- Use `v-slot` destructuring in the parent to access provided data
- Keep child components focused purely on presentation; the data provider handles all data logic

## Details

### Data Provider Pattern

The data provider pattern is a design pattern that complements the renderless component pattern in Vue by focusing on providing data and state management capabilities to components _without being concerned about how the data is rendered or displayed_.

In the data provider pattern, a data provider component encapsulates the logic for fetching, managing, and exposing data to its child components. The child components can then consume this data and use it in their own rendering or behavior.

This pattern promotes separation of concerns, as the data provider component takes care of data-related tasks, while the child components can focus on presentation and interaction.

Let's illustrate the data provider pattern with an example. Consider a simple application that displays the setup of a funny joke followed by its punchline. To keep the example self-contained, we'll use a local in-memory data source instead of depending on an external API.

```js
const jokes = [
  { id: 1, setup: "Why did the dev go broke?", punchline: "Because they used up all their cache." },
  { id: 2, setup: "Why do functions love TypeScript?", punchline: "Because it keeps their arguments in order." },
];
```

We'll first create a data provider component called `DataProvider` that will hold the responsibility of loading a joke. In the `<script>` section of the component, we'll import the `ref()` and `reactive()` functions from Vue, define a local data source, and set up `data` and `loading` reactive properties to capture the selected joke and loading state.

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

  const jokes = [
    { id: 1, setup: "Why did the dev go broke?", punchline: "Because they used up all their cache." },
    { id: 2, setup: "Why do functions love TypeScript?", punchline: "Because it keeps their arguments in order." },
  ];

  const data = reactive({
    setup: null,
    punchline: null,
  });

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

We can then create a `fetchJoke()` function in our `DataProvider` component to simulate loading data asynchronously.

```js
const fetchJoke = async () => {
  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 300));
    const jokeData = jokes[Math.floor(Math.random() * jokes.length)];
    data.setup = jokeData.setup;
    data.punchline = jokeData.punchline;
  } catch (error) {
    console.error("Error loading joke:", error);
  } finally {
    loading.value = false;
  }
};
```

With the fetch function ready, we can call it when the component mounts using the `onMounted()` lifecycle hook.

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

// ...

onMounted(() => {
  fetchJoke();
});
```

The **key** element in a data provider component is that its template consists purely of a single `<slot>` element. This slot will provide the fetched data and the relevant method to its child components using **scoped slots**.

```html
<template>
  <slot :data="data" :loading="loading" :fetchJoke="fetchJoke"></slot>
</template>
```

The `DataProvider` component passes `data`, `loading`, and `fetchJoke` as scoped slot props. This means any child component placed inside the `DataProvider` can access these properties.

Now, let's create a `JokeCard` component that will present the joke data.

```html
<template>
  <div class="joke-card">
    <p v-if="loading">Loading...</p>
    <div v-else>
      <p class="setup">{{ data.setup }}</p>
      <p class="punchline">{{ data.punchline }}</p>
    </div>
    <button @click="fetchJoke">Get Another Joke</button>
  </div>
</template>

<script setup>
  defineProps(["data", "loading", "fetchJoke"]);
</script>
```

The `JokeCard` component is a simple presentational component. It expects `data`, `loading`, and `fetchJoke` as props, and renders the joke data along with a button to fetch a new joke.

Now, to bring it all together, we use the `DataProvider` component in our `App` component. We wrap the `JokeCard` component inside the `DataProvider` and pass the scoped slot props to it:

```html
<template>
  <DataProvider v-slot="{ data, loading, fetchJoke }">
    <JokeCard :data="data" :loading="loading" :fetchJoke="fetchJoke" />
  </DataProvider>
</template>

<script setup>
  import DataProvider from "./components/DataProvider.vue";
  import JokeCard from "./components/JokeCard.vue";
</script>
```

With this setup, the `DataProvider` handles all data fetching and management, while the `JokeCard` focuses solely on displaying the data. This clean separation makes it easy to swap out the presentational component for a different one without touching the data-fetching logic.

The data provider pattern is especially useful when:

- Multiple components need to consume the same data but display it differently.
- You want to centralize data fetching logic without tightly coupling it to specific UI components.
- You want to keep your components focused on a single responsibility.

## Source

- [patterns.dev/vue/data-provider](https://patterns.dev/vue/data-provider)

### References

- [Scoped Slots | Vue Documentation](https://vuejs.org/guide/components/slots.html#scoped-slots)
- [Renderless Components | Vue Documentation](https://vuejs.org/guide/components/slots.html#renderless-components)

© patterns.dev · MIT · PatternsDev/skills

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

Все скиллы по теме «Фронтенд и UI» →
pinia-colada secondsky Скилл pinia-colada для управления асинхронным состоянием в Vue и Nuxt через useQuery и useMutation. Помогает при кешировании, SSR, инвалидации кеша и миграции с TanStack Vue Query. CX Codex +1 253установок nextjs-data-fetching giuseppe-trisciuoglio Скилл nextjs-data-fetching даёт готовые паттерны выборки данных в Next.js App Router: от серверных компонентов и ISR до интеграции с SWR и React Query. CX Codex +1 4 000установок nuxt-data Claude Skills Maintainers Скилл nuxt-data для работы с данными в Nuxt 4: композаблы, useFetch и useAsyncData, состояние через useState и Pinia. CX Codex +1 408установок tanstack-query-best-practices DeckardGer Скилл tanstack-query-best-practices для Claude Code собирает правила TanStack Query для React: ключи запросов, кеш, мутации и SSR. Включается при работе над загрузкой данных, чтобы соблюдать одну схему. CX Codex +1 13 400установок tanstack-query tanstack-skills Скилл подсказывает агенту, как работать с TanStack Query v5: кэширование, инвалидация, мутации и оптимистичные обновления. CX Codex +1 10 500установок react-query Mindrally Задаёт агенту правила работы с React Query: кэширование, фоновые обновления, инвалидация запросов и оптимистичные апдейты. CX Codex +1 1 500установок

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

Весь набор →
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установок container-presentational Скилл container-presentational учит разделять Vue-компоненты на контейнеры (логика, запросы) и презентационные (вёрстка). Презентационный компонент получает данные через props и не трогает состояние. CX Codex +1 205установок 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установок

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

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