Skip to content

Instantly share code, notes, and snippets.

@Hiroshiba
Created October 25, 2024 16:45
Show Gist options
  • Save Hiroshiba/08203482c6197a9d45190d0528beb35d to your computer and use it in GitHub Desktop.
Save Hiroshiba/08203482c6197a9d45190d0528beb35d to your computer and use it in GitHub Desktop.
Vueで、型を指定しつつprovide/injectできる関数を生成する。
import { InjectionKey, provide, inject } from "vue";
/**
* 型を指定しつつprovide/injectできる関数を生成する。
* 親のコンポーネントでprovideを行い、子孫コンポーネントでinjectを行うことで、
* 離れているコンポーネント間のデータの受け渡しが簡単になる。
*
* @example
* // 親コンポーネント
* const [provide, inject] = createProviderAndInjector<{ hoge: ref<number> }>();
* provide({ hoge: ref(1) });
*
* // 子孫コンポーネント
* const { hoge } = inject();
* console.log(hoge.value); // 1
*
* @returns [provide, inject]の形式で返す。
*/
export function createProviderAndInjector<
T extends Record<PropertyKey, unknown>,
>() {
const key = Symbol() as InjectionKey<T>;
function provide_(value: T) {
provide(key, value);
}
function inject_() {
const value = inject(key);
if (value == undefined) {
throw new Error("Provideされていません");
}
return value;
}
return [provide_, inject_] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment