cww
cww

Reputation: 653

Difference in watch properties vs $watch method in created event (Vue)

Is there any difference in watch properties vs $watch method in Vue? For example, I'm trying to understand why the Author use the $watch event instead of watch property in the code below.

 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)
    })
  },

If say I move the $watch as below, is there any difference?

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

Please advise.

Upvotes: 1

Views: 630

Answers (1)

Kapcash
Kapcash

Reputation: 6909

The watch options uses this.$watch method under the hood, so it's basically the same.

The only difference is that this.$watch returns a function you can call to stop the watcher:

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

...

queryWatcher() // Stop the watcher

There's no point of using this.$watch is you don't need that stop function so you can safely move them to the watch option property.

Upvotes: 1

Related Questions