Blog>
Snippets

Provide/Inject for Theming Components

Illustrate how to use provide and inject for passing theme-related data such as colors and fonts to components in a Vue.js 3 application.
const app = Vue.createApp({
  provide() {
    return {
      theme: {
        color: 'blue',
        font: 'Arial',
      }
    };
  }
});
This is the root Vue instance where the 'provide' option is used to define the theme object that includes color and font. This theme object is made available to all descendant components.
const childComponent = {
  inject: ['theme'],
  created() {
    console.log('The theme color is:', this.theme.color);
    console.log('The theme font is:', this.theme.font);
  }
};
This is a child component that uses the 'inject' option to access the theme object provided by an ancestor component. The theme data is accessed and logged once the component is created.
app.component('child-component', childComponent);

app.mount('#app');
This code registers the child component with the root Vue instance and mounts the Vue application to the '#app' element in the DOM.