#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 11 of 37medium

What is Provide/Inject in Vue?

Dependency injection for deep components.

What You'll Learn

  • provide() function
  • inject() function
  • Reactive provide

Basic Usage

code.jsJavaScript
// Parent component
import { provide } from 'vue'

provide('message', 'Hello from parent')
provide('count', ref(0))

// Deeply nested child
import { inject } from 'vue'

const message = inject('message')
const count = inject('count')

With Default Values

code.jsJavaScript
// If not provided, use default
const message = inject('message', 'Default message')

// Factory function for default
const config = inject('config', () => ({ theme: 'dark' }))

Reactive Provide

code.jsJavaScript
// Parent
const count = ref(0)
provide('count', count)

// Also provide update function
provide('updateCount', (value) => {
  count.value = value
})

// Child
const count = inject('count')
const updateCount = inject('updateCount')

TypeScript

code.tsTypeScript
import { InjectionKey } from 'vue'

const countKey: InjectionKey<Ref<number>> = Symbol()

// Parent
provide(countKey, ref(0))

// Child
const count = inject(countKey) // Typed!