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

provide-inject — скилл для Vue: dependency injection без prop drilling

Скилл provide-inject учит агента использовать provide() и inject() из Vue для передачи данных глубоко вложенным компонентам без прокидывания пропсов через каждый уровень.

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

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

Что делает provide-inject

Скилл объясняет агенту паттерн provide/inject для Vue: provide() в родительском компоненте делает данные доступными всем потомкам, inject() в дочерних компонентах получает их напрямую. Подходит для темы, локали, состояния авторизации — того, что нужно многим компонентам сразу. Работает на уровне приложения (app.provide()) или внутри дерева компонентов.

Скилл учит выбирать между пропсами и provide/inject: пропсы проще и явнее для локальных данных, provide/inject избавляет от prop drilling в глубоких деревьях, но усложняет отладку в больших приложениях с множеством провайдеров. Файл активен для всех .vue файлов проекта.

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

  • передать данные вложенным компонентам без пропсов на каждом уровне
  • настроить общую тему, локаль или данные авторизации для всего приложения
  • избавиться от prop drilling в глубоких деревьях компонентов Vue
  • сделать плагин с данными, доступными любому компоненту

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

  • Используй provide/inject для передачи темы всем компонентам в App.vue
  • Настрой app.provide() для локали в main.js
  • Перепиши этот компонент: замени prop drilling на provide/inject для данных авторизации

Как установить provide-inject

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill provide-inject -a claude-code

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

~/.claude/skills/provide-inject/SKILL.md

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

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

Вопросы о provide-inject

Как установить provide-inject в Claude Code?

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

Что делает скилл provide-inject?

Учит агента использовать Vue API provide() и inject() для передачи данных вложенным компонентам без прокидывания пропсов через каждый уровень дерева.

Когда не стоит использовать provide/inject?

Когда пропсы проще и понятнее (связь родитель-ребёнок), когда неявная зависимость мешает изолированному тестированию или когда уже подключён Pinia для управления состоянием.

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

SKILL.md · MIT
---
name: provide-inject
description: Teaches Vue's provide/inject API for dependency injection across components. Use when deeply nested components need access to ancestor data without threading props through intermediate layers.
paths:
  - "**/*.vue"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "composables"
  - "components"
---

# Provide/Inject

When managing data between parent and child components, Vue gives us the ability to use something known as **props** to pass data down from parent to child. Props can only flow in one direction, from parent components to child components (and further down). When state changes occur on parent elements, Vue will re-render components that depend on those values.

Using props works well in most cases. However, when working in large applications with a large number of components in the component tree, props can become hard to maintain since props need to be declared in _each and every component_ in the component tree.

## When to Use

- Use this when you need to pass data through deeply nested component trees without prop drilling
- This is helpful for application-wide data like themes, locale, or authentication state

## When NOT to Use

- For parent-child communication where props are simpler, more explicit, and easier to trace
- When the implicit dependency makes components harder to test in isolation or reuse outside the provider tree
- When a state management solution (Pinia) is already in place and provides the same shared state capability

## Instructions

- Use `provide()` in a parent or ancestor component to make data available to all descendants
- Use `inject()` in child components to access provided data
- Use app-level `app.provide()` for data needed across the entire application (e.g., plugins)
- Prefer props for data isolated to a specific set of components; use provide/inject for cross-cutting concerns
- Be aware that debugging can be harder with provide/inject in large apps with many providers

## Details

When considering how data can be managed between a large number of components, it's often best to work towards a solution that allows the management of application-level state in a maintainable and manageable manner (e.g. creating a reusable store, using Pinia, etc.). We talk about this in more detail in the [State Management](/vue/state-management) guide.

However, Vue also provides a certain pattern to help avoid the need for complex prop drilling in a Vue application known as the provide/inject pattern.

### Provide/Inject

The `provide()` function in Vue allows us to pass data through a component tree without the need to _prop-drill_ (i.e., pass props down manually at every level). On the other hand, the `inject()` option is used in child components to access the provided data or methods from their parent or any ancestor component.

We'll go through a simple example to illustrate how this can be done. Suppose we have a parent component called `App` that wants to share a piece of data with its child component, `ChildComponent`. Instead of passing this data as a prop, we can use `provide()` in the parent component to make the data available to all its child components.

```html
<template>
  <div id="app">
    <ChildComponent />
  </div>
</template>

<script setup>
  import { provide } from "vue";
  import ChildComponent from "./components/ChildComponent";

  provide("data", "Data from parent!");
</script>
```

We can then access this provided data in the `ChildComponent` with the help of the `inject()` function.

```html
<template>
  <div>
    <p>{{ data }}</p>
  </div>
</template>

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

  const data = inject("data");
</script>
```

By specifying `inject("data")` in the child component (`ChildComponent`), we directly access the provided `data` value from the parent component. We then bind `data` to the template to display its value.

With provide/inject, we would notice the same behavior even if we had numerous child components within the component hierarchy tree. Data from the parent `<App />` component will be rendered in any deeply nested child component without the need to prop-drill data through every component in the tree, thanks to provide/inject!

In addition to being able to `provide()` data from a parent component, we can lift the `provide()` up to the app level as well (i.e. where we instantiate our Vue application).

```js
import { createApp } from "vue";
import App from "./App.vue";
import "./styles.css";

const app = createApp(App);

// app-level provide
app.provide("data", "Data from parent!");

app.mount("#app");
```

Since app-level provides make data available to _all_ components, they are often helpful when creating [plugins](https://vuejs.org/guide/reusability/plugins.html) — self-contained code that adds functionality to the entire Vue app.

### Props vs. provide/inject

When do we choose between props and the provide/inject pattern? Both approaches have their advantages and disadvantages.

#### With props:

- We follow a clear pattern of passing data incrementally from one level to another (advantage).
- However, if our component hierarchy tree contains a large number of components, the process of passing props data one level at a time can become cumbersome (disadvantage).

#### With provide/inject

- Child components can directly access data from parent components located multiple levels above, eliminating the need for passing down data at each level (advantage).
- However, when bugs arise, debugging can be more challenging with provide/inject. This challenge becomes more pronounced in large-scale applications with numerous different providers (disadvantage).

The provide/inject pattern is most suitable for application-wide client data, such as theme information, locale/language preferences, and user authentication details. These types of data are better managed with provide/inject since any component within the application may require access to them at any given time.

On the other hand, props are ideal when data needs to be isolated within a specific set of components only.

## Source

- [patterns.dev/vue/provide-inject](https://patterns.dev/vue/provide-inject)

### References

- [Provide / Inject | Vue Documentation](https://vuejs.org/guide/components/provide-inject.html)

© patterns.dev · MIT · PatternsDev/skills

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

Все скиллы по теме «Фронтенд и UI» →
ui-design-patterns manutej Скилл ui-design-patterns для Claude Code — справочник по паттернам навигации, форм, вывода данных, обратной связи и доступности. Помогает выбрать паттерн или проверить существующий интерфейс. CX Codex +1 854установок angular-development manutej Скилл angular-development для Claude Code и других агентов: компоненты, сервисы, DI, роутинг, формы и Signals. Удерживает агент от старых паттернов при написании кода на Angular. CX Codex +1 464установок software-patterns bobmatnyc Скилл software-patterns для Claude Code и Codex: ведёт по дереву решений к паттерну под конкретную проблему — связанность, отказоустойчивость, границы сервисов. Разбирает код с запахами и циклическими вызовами между сервисами. CX Codex +1 390установок nuxt-ui nuxt Помогает агенту собирать интерфейсы на базе @nuxt/ui v4, настраивать темы Tailwind CSS и правильно выбирать компоненты библиотеки. CX Codex +1 20 500установок web-component-design Seth Hobson Скилл web-component-design для Claude Code проектирует компоненты для React, Vue и Svelte. Формирует библиотеки UI и дизайн-системы, помогает рефакторить старые компоненты. CX Codex +1 13 167установок reka-ui onmax Справочник Reka UI, библиотеки unstyled-компонентов Vue 3 с поддержкой доступности. Подгружает описание примитивов для форм, диалогов и меню по запросу. CX Codex +1 7 500установок

Из того же набора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установок 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установок

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

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