대시보드에 다양한 컴포넌트들을 배치하고 놓고 기간의 업데이트에 따라 컴포넌트들의 데이터를 변경해야했다.
가장 단순하게는 기간을 관리하는 컨트롤러에서 defineEmits()
를 사용하여 부모로 데이터를 올린후 이벤트를 받아 부모컴포넌트에서 자식컴포넌트로 props
를 이용한 데이터 바인딩을 하려고 하였다.
그렇게 단순하게 끗? 하려고 하는 순간 컨트롤러.vue -> 부모.vue -> 자식.vue 의 과정이 너무 불필요하다고 하셨다... (생각해보니 맞는것 같음)
또한 사용하는 자식컴포넌트마다 defindProps()
를 사용하는게 마음에 들지 않았다.
emit
를 보내기//controller.vue <script setup>
const emit = defineEmits['period]
watch(period, ()=>{
emit('period', period.value)
})
//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>
이 방법은 mitt 라이브러리를 설치 후 createApp(App)을 통해 전역으로 provide('emitter')해줘야함!
emitter
를 보내기//controller.vue <script setup>
watch(period, ()=>{
emitter.emit('period', period.value)
})
//home.vue, <script setup>
const period = ref([]);
onBeforeMout(()=>{
emitter.on('period', (period)=>{
period.value = period;
})
})
이렇게 받아서 각 period
를 컴포넌트들로 보내는 방법.
사실 이것 또한 처음에 시도했던 방법과 별 다를것이 없었다. 떼잉
간단한 데이터에 비해 Pinia를 통해 store 를 하기엔 덩치가 너무 커져서 포기
import { ref } from 'vue';
const bus = ref(new Map());
export const useEventBus = () => {
const emit = (event, args) => {
bus.value.set(event, args);
};
return { emit, bus };
};
import { useEventBus } from '@/modules/dashboard/eventBus';
const { emit } = useEventBus();
watch(period, ()=>{
emit('period', period.value)
})
import { useEventBus } from '@/modules/dashboard/eventBus';
const { bus } = useEventBus();
const setPeriod = computed(() => {
return bus.value.get('period');
});
Map()
을 이용하여 여러 종류의 함수를 넣고 가져다 쓸 수 있다.
watch를 걸었기 때문에 이벤트가 발생할 때 마다 computed를 통해 화면에 보여주는 용도로만 사용하기에 간단하게 쓸 수 있었는데 추가적으로 api를 호출할때는 싸이클을 한번 자세하게 확인하고 쓸 수 있을 것 같다.