반응형
이 포스팅에서 작성하는 내용은 프로젝트로 배우는 Vue.js 3 에서 발췌하였습니다.
Lifecycle Hooks
onBeforeMount
: mount 전onMounted
: mount 후onBeforeUpdate
: (state) update 전onUpdated
: (state) update 후onBeforeUnmount
: mount 해제되기 전onUnmounted
: mount 해제 후onErrorCaptued
: error 발생 후
...
<script>
...
export default {
components: {
...
},
setup() {
onUnmounted(() => {
console.log('onUnmounted');
});
}
...
</script>
...
Lifecycle Hooks 흐름도 : https://vuejs.org/guide/essentials/lifecycle.html#lifecycle-diagram
공식 문서 : https://vuejs.org/api/composition-api-lifecycle.html
함수 재사용
여러 컴포넌트에서 동일한 로직을 사용하는 경우,
동일한 로직을 담은 js 파일을 생성하고 사용하면 유지보수 측면에서 상당히 좋다.
어떤식으로 재사용하면 좋은 지 아래의 예제를 보면서 확인해보자.
Toast
: 알림창 컴포넌트
기본 로직
message
: 알림 메시지isShow
:true -> 알림 표시
/false -> 알림 숨김
재사용 적용 전
알림창을 호출하는 main.vue
main.vue
<template>
...
<Toast
v-if="isShow"
:message="message"
/>
</template>
<script>
import { ref, onUnmounted } from 'vue';
export default {
setup(props) {
const message = ref('');
const isShow = ref(false);
const timeout = ref(null);
const showToast = (message) => {
message.value = message;
isShow.value = true;
timeout.value = setTimeout(() => {
message.value = '';
isShow.value = false;
}, 3000)
}
onUnmounted(() => {
clearTimeout(timeout.value);
})
return {
message,
isShow,
showToast
}
}
}
</script>
재사용 적용 후
toastUtils.js 라는 파일을 생성해서 해당 파일에 위의 알림을 호출하는 로직 및 변수를 작성
toastUtils.js
import { ref, onUnmounted } from 'vue';
export const toastUtils = () => {
const message = ref('');
const isShow = ref(false);
const timeout = ref(null);
const showToast = (message) => {
message.value = message;
isShow.value = true;
timeout.value = setTimeout(() => {
message.value = '';
isShow.value = false;
}, 3000)
}
onUnmounted(() => {
clearTimeout(timeout.value);
})
return {
message,
isShow,
showToast
}
}
위의 toastUtils.js 를 이용해서 알림창을 컨트롤하는 main.vue
main.vue
<template>
...
<Toast
v-if="isShow"
:message="message"
/>
</template>
<script>
import { toastUtils } from '@/toastUtils'; // 각자 생성한 경로에 맞게 설정
export default {
setup(props) {
const { message, isShow, timeout } = toastUtils(); // 단순히 toastUtils 에서 가져옴
return {
message,
isShow,
showToast
}
}
}
</script>
반응형
'FE > Vue.js' 카테고리의 다른 글
[Vue.js 3] vuex 예제 (0) | 2023.10.29 |
---|---|
[Vue.js 3] Teleport, Slot, v-model binding, toRefs (0) | 2023.10.01 |
[Vue.js 3] Router / Event Bubbling / 객체 비교 (0) | 2023.07.30 |
[Vue.js 3] Computed, async / await, watchEffect, watch (0) | 2023.07.16 |
[Vue.js 3] v-bind / v-model, v-for, v-show / v-if, emit / props (0) | 2023.07.09 |