Blog>
Snippets

Provide/Inject with Computed Properties

Showcase how to provide computed properties to descendant components and how they can be injected and used in templates.
// ParentComponent.vue
<template>
  <div>
    <child-component />
  </div>
</template>

<script>
import { defineComponent, computed, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default defineComponent({
  components: { ChildComponent },
  setup() {
    const baseValue = ref(10);

    // Define a computed property
    const providedComputed = computed(() => baseValue.value * 2);

    // Provide the computed property to descendant components
    provide('providedComputed', providedComputed);

    return {};
  },
});
</script>
This is the parent component that provides a computed property to its descendants. It multiplies a base value by 2 and provides it for injection by descendant components.
// ChildComponent.vue
<template>
  <div>
    Computed Value: {{ computedValue }}
  </div>
</template>

<script>
import { defineComponent, inject } from 'vue';

export default defineComponent({
  setup() {
    // Inject the computed property provided by the ancestor component
    const computedValue = inject('providedComputed');

    return { computedValue };
  },
});
</script>
This is the child component that injects the computed property provided by its ancestor. It accesses the injected computed property and uses it within its template.