생계유지형 개발자/JS Framework
[vue] 컴포넌트에서 watch() 사용하여 router 이동 감지하기
이 가을
2020. 1. 8. 11:29
상위 컴포넌트에서 router path가 변경되어 하위 컴포넌트가 변경될 때 접근로그를 기록하기 위해서, 컴포넌트 내에서 router의 변경을 감지할 필요가 있었다.
상위 컴포넌트의 watch 함수에 $route를 정의함으로써 router-view가 변경될 때마다 감지할 수 있었다.
watch: {
$route(to, from) {
// .....
}
}
- 상위 컴포넌트 : DefaultContainer
- 하위 컴포넌트 : LoggingCenterContainer, LoggingCenterAccessLog, LoggingCenterActionLog
router/index.js
/* router/index.js */
const routes = {
path: '/lc',
component: DefaultContainer,
children: [
{ path: 'container', component: LoggingCenterContainer },
{ path: 'access-log', component: LoggingCenterAccessLog },
{ path: 'action-log', component: LoggingCenterActionLog },
],
}
DefaultContainer.vue
/* DefaultContainer.vue */
<template>
<div class="app">
<div class="container-fluid">
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
{ ... },
watch: {
$route(to, from) {
if (to.path != from.path) {
/* router path가 변경될 때마다 서버로 접근로그를 저장한다. */
axios.post("/lc/access-log");
}
}
}
}
</script>