Blog>
Snippets

Provide/Inject with Default Values

Demonstrate how to specify default values for the injected data in case the provide is not present in any ancestor component in the Vue.js 3 component hierarchy.
const app = Vue.createApp({});

// Child component
app.component('child-component', {
    inject: {
        theme: {
            default: 'light'
        }
    },
    template: `<div>Theme: {{ theme }}</div>`
});

// Parent component
app.component('parent-component', {
    provide() {
        return {
            // Uncomment the next line to provide 'theme' value from the parent
            // theme: 'dark'
        };
    },
    template: `<child-component></child-component>`
});

app.mount('#app');
This example includes two components: a parent-component and a child-component. In the child component, we use inject to define a 'theme' property expecting it from an ancestor provider. The default value for 'theme' is specified as 'light' in case there is no provider up the component tree. In the parent component, it has a provide function that could supply an object with the 'theme' property, but it's commented out. Therefore, when the child component tries to inject 'theme', it will use the default value since the parent does not provide it. The app is then mounted to an element with the id 'app'.