Skip to content

Provide/inject #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
Mar 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ const sidebar = {
'/guide/component-registration',
'/guide/component-props',
'/guide/component-custom-events',
'/guide/component-slots'
'/guide/component-slots',
'/guide/component-provide-inject'
]
}
]
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
112 changes: 112 additions & 0 deletions src/guide/component-provide-inject.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Provide / inject

> This page assumes you've already read the [Components Basics](components.md). Read that first if you are new to components.

Usually, when we need to pass data from the parent to child component, we use [props](component-props.md). Imagine the structure where you have some deeply nested components and you only need something from the parent component in the deep nested child. In this case, you still need to pass the prop down the whole component chain which might be annoying.

For such cases, we can use the `provide` and `inject` pair. Parent components can serve as dependency provider for all its children, regardless how deep the component hierarchy is. This feature works on two parts: parent component has a `provide` option to provide data and child component has an `inject` option to start using this data.

![Provide/inject scheme](/images/components_provide.png)

For example, if we have a hierarchy like this:

```
Root
└─ TodoList
├─ TodoItem
└─ TodoListFooter
├─ ClearTodosButton
└─ TodoListStatistics
```

If we want to pass the length of todo-items directly to `TodoListStatistics`, we would pass the prop down the hierarchy: `TodoList` -> `TodoListFooter` -> `TodoListStatistics`. With provide/inject approach, we can do this directly:

```js
const app = Vue.createApp({})

app.component('todo-list', {
data() {
return {
todos: ['Feed a cat', 'Buy tickets']
}
},
provide: {
user: 'John Doe'
},
template: `
<div>
{{ todos.length }}
<!-- rest of the template -->
</div>
`
})

app.component('todo-list-statistics', {
inject: ['foo'],
created() {
console.log(`Injected property: ${this.user}`) // > Injected property: John Doe
}
})
```

However, this won't work if we try to provide some Vue instance property here:

```js
app.component('todo-list', {
data() {
return {
todos: ['Feed a cat', 'Buy tickets']
}
},
provide: {
todoLength: this.todos.length // this will result in error 'Cannot read property 'length' of undefined`
},
template: `
...
`
})
```

To access Vue instance properties, we need to convert `provide` to be a function returning an object

```js
app.component('todo-list', {
data() {
return {
todos: ['Feed a cat', 'Buy tickets']
}
},
provide() {
return {
todoLength: this.todos.length
}
},
template: `
...
`
})
```

This allows us to more safely keep developing that component, without fear that we might change/remove something that a child component is relying on. The interface between these components remains clearly defined, just as with props.

In fact, you can think of dependency injection as sort of “long-range props”, except:

- parent components don’t need to know which descendants use the properties it provides
- child components don’t need to know where injected properties are coming from

## Working with reactivity
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've started this chapter here but the more I work on it the more I think it should belong to Composition API. Maybe it would be a good idea to just state provide/inject is not reactive by default and say that if you want to make it reactive, you should look into Composition API chapter Making provide/inject reactive or something like this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel same, we can introduce to idea here and expand on reactivity on composition API section. However, in my opinion, the following section should be here and we can further link it composition API section.


In the example above, if we change the list of `todos`, this change won't be reflected in the injected `todoLength` property. This is because `provide/inject` bindings are _not_ reactive by default. We can change this behavior by passing a `ref` property or `reactive` object to `provide`. In our case, if we want to react to changes in the ancestor component, we need to assign a Composition API `computed` property to our provided `todoLength`:

```js
app.component('todo-list', {
// ...
provide() {
return {
todoLength: Vue.computed(() => this.todos.length)
}
}
})
```

In this, any change to `todos.length` will be reflected correctly in the components, where `todoLength` is injected. Read more about `reactive` provide/inject in the [Composition API section](TODO)
53 changes: 5 additions & 48 deletions src/guide/component-slots.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ To provide content to named slots, we need to use the `v-slot` directive on a `<
<template v-slot:default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:default>
</template>

<template v-slot:footer>
<p>Here's some contact info</p>
Expand Down Expand Up @@ -364,9 +364,10 @@ This can make the template much cleaner, especially when the slot provides many
You can even define fallbacks, to be used in case a slot prop is undefined:

```html
<current-user v-slot="{ user = { firstName: 'Guest' } }">
{{ user.firstName }}
</current-user>
<todo-list v-slot="{ item = 'Placeholder' }">
<i class="fas fa-check"></i>
<span class="green">{{ todo }}<span>
</todo-list>
```

## Dynamic Slot Names
Expand Down Expand Up @@ -418,47 +419,3 @@ Instead, you must always specify the name of the slot if you wish to use the sho
<span class="green">{{ item }}<span>
</todo-list>
```

## Other Examples

**Slot props allow us to turn slots into reusable templates that can render different content based on input props.** This is most useful when you are designing a reusable component that encapsulates data logic while allowing the consuming parent component to customize part of its layout.

For example, we are implementing a `<todo-list>` component that contains the layout and filtering logic for a list:

```html
<ul>
<li v-for="todo in filteredTodos" v-bind:key="todo.id">
{{ todo.text }}
</li>
</ul>
```

Instead of hard-coding the content for each todo, we can let the parent component take control by making every todo a slot, then binding `todo` as a slot prop:

```html
<ul>
<li v-for="todo in filteredTodos" v-bind:key="todo.id">
<!--
We have a slot for each todo, passing it the
`todo` object as a slot prop.
-->
<slot name="todo" v-bind:todo="todo">
<!-- Fallback content -->
{{ todo.text }}
</slot>
</li>
</ul>
```

Now when we use the `<todo-list>` component, we can optionally define an alternative `<template>` for todo items, but with access to data from the child:

```html
<todo-list v-bind:todos="todos">
<template v-slot:todo="{ todo }">
<span v-if="todo.isComplete">✓</span>
{{ todo.text }}
</template>
</todo-list>
```

However, even this barely scratches the surface of what scoped slots are capable of. For real-life, powerful examples of scoped slot usage, we recommend browsing libraries such as [Vue Virtual Scroller](https://github.com/Akryum/vue-virtual-scroller) or [Vue Promised](https://github.com/posva/vue-promised)