컴포지션 API 사용하여 event-bus 간지나게 태우기

Heina·2024년 3월 13일
0
post-thumbnail

고뇌의 시작

대시보드에 다양한 컴포넌트들을 배치하고 놓고 기간의 업데이트에 따라 컴포넌트들의 데이터를 변경해야했다.

가장 단순하게는 기간을 관리하는 컨트롤러에서 defineEmits()를 사용하여 부모로 데이터를 올린후 이벤트를 받아 부모컴포넌트에서 자식컴포넌트로 props를 이용한 데이터 바인딩을 하려고 하였다.

그렇게 단순하게 끗? 하려고 하는 순간 컨트롤러.vue -> 부모.vue -> 자식.vue 의 과정이 너무 불필요하다고 하셨다... (생각해보니 맞는것 같음)

또한 사용하는 자식컴포넌트마다 defindProps()를 사용하는게 마음에 들지 않았다.

시도방법1. defineEmits, defindProps 사용하기

1. 컨트롤러에서 watch를 통해 기간데이터가 변경 될 때 마다 emit를 보내기

//controller.vue <script setup>

const emit = defineEmits['period]

watch(period, ()=>{
emit('period', period.value)
})

2. 부모 컴포넌트에서 받기

//home.vue, <script setup>

<template>
  <controller @period="period"/>
  <component :period='period'/>
</template>

<script setup>
const period = ref([]);

onBeforeMout(()=>{
  emitter.on('period', (period)=>{
    period.value = period;
  })
})
</script>

시도방법2. mitt를 이용한 emitter이용하기

이 방법은 mitt 라이브러리를 설치 후 createApp(App)을 통해 전역으로 provide('emitter')해줘야함!

1. 컨트롤러에서 watch를 통해 기간데이터가 변경 될 때 마다 emitter를 보내기

//controller.vue <script setup>

watch(period, ()=>{
emitter.emit('period', period.value)
})

2. 부모 컴포넌트에서 데이터 받기

//home.vue, <script setup>

const period = ref([]);

onBeforeMout(()=>{
  emitter.on('period', (period)=>{
    period.value = period;
  })
})

이렇게 받아서 각 period를 컴포넌트들로 보내는 방법.
사실 이것 또한 처음에 시도했던 방법과 별 다를것이 없었다. 떼잉

시도방법3. store 사용하기

간단한 데이터에 비해 Pinia를 통해 store 를 하기엔 덩치가 너무 커져서 포기

시도방법4. 컴포지션 API 사용하여 이벤트 버스 만들기

1. eventBus용 js 생성하기

import { ref } from 'vue';

const bus = ref(new Map());

export const useEventBus = () => {
  const emit = (event, args) => {
    bus.value.set(event, args);
  };

  return { emit, bus };
};

2. 컨트롤러에서 이벤트버스에 함수 태워보내기

import { useEventBus } from '@/modules/dashboard/eventBus';

const { emit } = useEventBus();

watch(period, ()=>{
emit('period', period.value)
})

3. 받을 곳에서 computed를 통해 실시간으로 감지하여 화면에 보여주기

import { useEventBus } from '@/modules/dashboard/eventBus';

const { bus } = useEventBus();

const setPeriod = computed(() => {
  return bus.value.get('period');
});

Map() 을 이용하여 여러 종류의 함수를 넣고 가져다 쓸 수 있다.
watch를 걸었기 때문에 이벤트가 발생할 때 마다 computed를 통해 화면에 보여주는 용도로만 사용하기에 간단하게 쓸 수 있었는데 추가적으로 api를 호출할때는 싸이클을 한번 자세하게 확인하고 쓸 수 있을 것 같다.

event-bus 참고 stack overflow

0개의 댓글