Blog>
Snippets

Provide/Inject with a Dynamic Key

Use a dynamic key in both the provide and inject mechanisms to conditionally share data based on certain criteria.
const DynamicKeySymbol = Symbol();

Vue.component('provider-component', {
  // The provider component
  provide() {
    // Using a dynamic key based on a condition
    const key = this.conditionMet ? DynamicKeySymbol : null;

    // Returning an object with the dynamic key
    return key ? { [key]: 'Provided Value' } : {};
  },
  data() {
    return {
      conditionMet: true // or false based on some logic
    };
  }
});
In the 'provider-component', we define a dynamic key using a Symbol and conditionally provide it based on the truthiness of 'conditionMet'.
Vue.component('consumer-component', {
  // The consumer component
  inject: {
    // Inject using a dynamic key
    dynamicValue: {
      from: DynamicKeySymbol,
      default: 'Default Value' // Fallback if the key isn't provided
    }
  },
  mounted() {
    // Accessing the injected value
    console.log(this.dynamicValue); // Outputs either the provided value or the default
  }
});
In the 'consumer-component', we use 'inject' to access the value provided by the 'provider-component' using the dynamic key, which is a Symbol. We also provide a default value as a fallback.