Blog>
Snippets

Providing and Injecting Multiple Values

Showcase how to provide and inject multiple pieces of data from a single component, organizing them with the use of an object or multiple provide calls.
const { provide, inject } = require('vue');

// Parent component providing multiple values
const ParentComponent = {
    setup() {
        // Providing multiple values separately
        provide('providedValue1', 'This is value 1');
        provide('providedValue2', 'This is value 2');

        // Alternatively, providing an object with multiple values
        const providedValues = {
            value1: 'This is value 1',
            value2: 'This is value 2'
        };
        provide('providedValues', providedValues);
    }
};
This code registers a parent component that uses the `provide` function twice to pass down 'providedValue1' and 'providedValue2' to any descendant components. It also demonstrates providing an object 'providedValues' as a single injection point for multiple values.
// Child component injecting multiple values
const ChildComponent = {
    setup() {
        // Injecting multiple values separately
        const injectedValue1 = inject('providedValue1');
        const injectedValue2 = inject('providedValue2');

        // Output the injected values
        console.log(injectedValue1); // 'This is value 1'
        console.log(injectedValue2); // 'This is value 2'

        // Alternatively, injecting the provided object
        const { value1, value2 } = inject('providedValues');

        // Output the values from the injected object
        console.log(value1); // 'This is value 1'
        console.log(value2); // 'This is value 2'

        return { injectedValue1, injectedValue2 };
    }
};
This code defines a child component that uses the `inject` function to receive 'providedValue1' and 'providedValue2' from any ancestor component. Additionally, it shows how to inject an object 'providedValues' and destructure it to obtain both values.