메인 Vue화면에 컴포넌트 A,B,C...가 구성되어 있다.
API로 받아온 데이터로 각 컴포넌트간에 이벤트를 주고 받는것을 InjectionKey를 활용한 기록을 남겨본다.
기본적으로 injectionKeys.js라는 파일을 만들어 다음과 같이 전역적으로 사용할 수 있게 한다.
/** @type {import("vue").InjectionKey} */
export const myInjectionKey = Symbol('myComponent');
Main.vue
const { on, trigger } = createEventHook();
const selectedData = shallowRef();
provide(myInjectionKey,{
data : computedEager(() => selectedData.value),
set(data){
selectedData.value = {...data};
},
clear(){
selectedData.value = {};
},
on,
trigger,
});
선언한 InjectionKey에 Provide, Injection을 사용해 부모 -> 자식 A, 자식 A -> 부모 -> 자식 B 등의 이벤트 전달을 할 수 있다.
COMPONENTA.vue
const parent = inject(myInjectionKey);
parent.set(data)
parent.clear()
parent.on(event)
inject를 이용해 키를 주입받고 부모로 전달할 이벤트를 사용한다.
COMPONENTB.vue
const parent = inject(myInjectionKey);
parent.trigger()
마찬가지로 B에서도 같은 코드를 작성한다. 여기서 B의 수행을 마치고 이벤트를 발생시켜 A에 전달할때 vueuse의 CreateEventHook의 on, trigger를 사용한다.
on을 이용해 이벤트를 A에서 저장하고 B에서 trigger를 사용하면 A의 이벤트가 호출된다.