Vue Class Component / router event 처리

뷰 클래스 타입으로 뷰 클래스 타입으로 작성시 아래와 같은 이벤트를 처리할 경우 그냥 사용하면 안되고 hooks를 추가해 주어야 한다.


'beforeRouteEnter',
'beforeRouteLeave',
'beforeRouteUpdate'

-  최상단에 class-component-hook.js 파일 생성

// class-component-hooks.js
import Component from 'vue-class-component'

// Register the router hooks with their names
Component.registerHooks([
  'beforeRouteEnter',
  'beforeRouteLeave',
  'beforeRouteUpdate'
])

 

- 실제 vue 페이지에서 함수 선언

import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class HelloWorld extends Vue {
  // The class component now treats beforeRouteEnter,
  // beforeRouteUpdate and beforeRouteLeave as Vue Router hooks
  beforeRouteEnter(to, from, next) {
    console.log('beforeRouteEnter')
    next()
  }

  beforeRouteUpdate(to, from, next) {
    console.log('beforeRouteUpdate')
    next()
  }

  beforeRouteLeave(to, from, next) {
    console.log('beforeRouteLeave')
    next()
  }
}

 

- 메인 js에서 import 

// main.js

// Make sure to register before importing any components
import './class-component-hooks'

import Vue from 'vue'
import App from './App'

new Vue({
  el: '#app',
  render: h => h(App)
})

 

참고 : https://class-component.vuejs.org/guide/additional-hooks.html