If you use provide
and inject
a lot in your apps, you can run into trouble if your keys are simple strings:
// injectionKeys.jsexport const AUTH_USER_KEY = 'USER';// some injections later...export const CURRENT_USER_KEY = 'USER';
Name collisions and typos are extremely hard to track down.
But there's a better way, using symbols:
// injectionKeys.jsexport const AUTH_USER_KEY = Symbol('USER');// some injections later...export const CURRENT_USER_KEY = Symbol('USER');
Every symbol is unique, so we no longer have to worry about name collisions.
But now we need to pass these symbols around so we can reuse them easily:
// In a Vue component far, far, away...import { inject } from 'vue';import { AUTH_USER_KEY } from './injectionKeys.js';const user = inject(AUTH_USER_KEY);