동작하는 범위에 따라 세 가지로 나뉜다.
router.beforeEach()를 사용하여 설정router.beforeEach()가 호출됨next()를 호출해야함// router/index.js
router.beforeEach((to, from, next) => {
// 로그인 여부
const isLoggedIn = false;
// 로그인이 필요한 페이지
const authPages = ['hello']
// 로그인이 필요한 사이트인지 확인
const isAuthRequired = authPages.includes(to.name)
if (isAuthRequired && !isLoggedIn) {
// 로그인이 필요한 경우
next({ name: 'login' })
} else {
// 로그인이 되어있다면
next()
}
})
로그인 하지 않아도 되는 페이지를 모아둘수도 있음
router.beforeEaxh((to, from, next) => {
const allowAllPages = ['login']
const isAuthRequired = !allowAllPages.includes(to.name)
}
beforeEnter()
이미 로그인 되어있는 경우 HomeView로 이동하도록 처리
// router/index.js
// 임시로 로그인 상태 표시
const isLoggedIn = true;
const routes = [
//...
{
path: '/login',
name: 'login',
component: LoginView,
beforeEnter(to, from, next) {
if (isLoggedIn === true) {
next({ name: 'home' })
} else {
next()
}
}
}
]
beforeRouteUpdate()
$route.params에 있는 데이터를 새로 가져오지 못함beforeRouteUpdate()로 params의 변화를 감지하게 함// views/HelloView.vue
<script>
export default {
name: 'HelloView',
data() {
return {
userName: this.$route.params.userName,
};
},
beforeRouteUpdate(to, from, next) {
this.userName = to.params.userName
next()
}
};
</script>