Search code examples
vue.jsvue-mixin

Is a watch property in vue a lifecycle hook?


Is any watch property included in vuejs lifecycle hooks?

Here you can see this excerpt from codepen:

const myMixin = {
  methods: {
    increment(){
      console.log('methods from mixins')
      this.myData+=2
    }
  },
  watch:{
    myData(){
      console.log('watcher from mixins')
    }
  }
}

new Vue({
  el: '#app',
  mixins:[myMixin],
  data: function () {
    return {
      myData: 0
    }
  },
  methods:{
    increment(){
      console.log('methods from comp')
      this.myData++
    }
  },
  watch:{
    myData(){
      console.log('watcher from component')
    }
  }
});

myData watcher from myMixin and the component's is called. However normal method from component is overridden.

In the documentation said:

Hook functions with the same name are merged into an array so that all of them will be called. Mixin hooks will be called before the component’s own hooks.

But, watch is not a hook functions / lifecycle hooks right?


Solution

  • As the documentation states,

    When a mixin and the component itself contain overlapping options, they will be “merged” using appropriate strategies.

    For example, data objects undergo a recursive merge, with the component’s data taking priority in cases of conflicts.

    It's expected that watch option will be merged as well as data option, and this is what happens in listed example.