programing

생성된 이벤트의 워치 속성과 $watch 메서드의 차이(Vue)

coolbiz 2022. 8. 14. 11:04
반응형

생성된 이벤트의 워치 속성과 $watch 메서드의 차이(Vue)

Vue에서는 워치 속성과 $watch 방식의 차이가 있습니까?예를 들어, 작성자가 아래 코드의 watch 속성 대신 $watch 이벤트를 사용하는 이유를 이해하려고 합니다.

 created () {
    const routes = this.mainMenu.find(item => item.path === '/')
    this.menus = (routes && routes.children) || []
    // 处理侧栏收起状态
    this.$watch('collapsed', () => {
      this.$store.commit(SIDEBAR_TYPE, this.collapsed)
    })
    this.$watch('isMobile', () => {
      this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
    })
  },

$watch를 아래와 같이 옮기면 차이가 있나요?

 watch: {
    isMobile : function(value) {
       this.$store.commit(TOGGLE_MOBILE_TYPE, value)
    },
    collapsed : function(value) {
       this.$store.commit(SIDEBAR_TYPE, value)
    }
 },
 created () {
 }

조언 부탁드립니다.

watch옵션 사용this.$watch보닛 밑의 수법, 그러니까 기본적으로 똑같아요.

유일한 차이점은 이다.this.$watch는 워처를 정지하기 위해 호출할 수 있는 함수를 반환합니다.

const queryWatcher = this.$watch('$route.query', doSomethingFunction)

...

queryWatcher() // Stop the watcher

사용해도 소용없다this.$watch정지 기능이 필요 없기 때문에 안전하게 이동시킬 수 있습니다.watch옵션 속성.

언급URL : https://stackoverflow.com/questions/68176042/difference-in-watch-properties-vs-watch-method-in-created-event-vue

반응형