Provide / Inject

This guide assumes that you have already read the Composition API Introduction and Reactivity Fundamentals. Read that first if you are new to Composition API.

We can use provide / inject with the Composition API as well. Both can only be called during setup() with a current active instance.

For example, if we want to provide a book name on the root component and inject it on the child component:

  1. import { provide, inject } from 'vue'
  2. const RootComponent = {
  3. setup() {
  4. provide('book', 'Vue 3 guide')
  5. }
  6. }
  7. const MyBook = {
  8. setup() {
  9. const book = inject(
  10. 'book',
  11. 'Eloquent Javasctipt' /* optional default value */
  12. )
  13. return {
  14. book
  15. }
  16. }
  17. }

inject accepts an optional default value as the 2nd argument. If a default value is not provided and the property is not found on the provide context, inject returns undefined.

If we need to provide or inject multiple values, we can do this with a subsequent call of provide or inject respectively:

  1. import { provide, inject } from 'vue'
  2. const RootComponent = {
  3. setup() {
  4. provide('book', 'Vue 3 guide')
  5. provide('year', '2020')
  6. }
  7. }
  8. const MyBook = {
  9. setup() {
  10. const book = inject(
  11. 'book',
  12. 'Eloquent Javasctipt' /* optional default value */
  13. )
  14. const year = inject('year')
  15. return {
  16. book,
  17. year
  18. }
  19. }
  20. }

Injection Reactivity

To retain reactivity between provided and injected values, we can use a ref or reactive when providing a value:

  1. import { ref, reactive } from 'vue'
  2. // in provider
  3. setup() {
  4. const book = reactive({
  5. title: 'Vue 3 Guide',
  6. author: 'Vue Team'
  7. })
  8. const year = ref('2020')
  9. provide('book', book)
  10. provide('year', year)
  11. }
  12. // in consumer
  13. setup() {
  14. const book = inject('book')
  15. const year = inject('year')
  16. return { book, year }
  17. }

Now, when either book or year are changed on the provider component, we can observe them changing on the component where they are injected.

WARNING

We don’t recommend mutating a reactive property where it’s injected as it’s breaking Vue one-direction data flow. Instead, try to either mutate values where they are provided or provide a method to mutate them

  1. import { ref, reactive } from 'vue'
  2. // in provider
  3. setup() {
  4. const book = reactive({
  5. title: 'Vue 3 Guide',
  6. author: 'Vue Team'
  7. })
  8. function changeBookName() {
  9. book.title = 'Vue 3 Advanced Guide'
  10. }
  11. provide('book', book)
  12. provide('changeBookName', changeBookName)
  13. }
  14. // in consumer
  15. setup() {
  16. const book = inject('book')
  17. const changeBookName = inject('changeBookName')
  18. return { book, changeBookName }
  19. }