Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable vue.js watcher while created/mounted methods are yet to be finished?

I would like to disable watcher, so it doesn't trigger certain watcher when created or mounted finish and enable it after these done. What is the proper way to achieve this?

like image 663
tomJO Avatar asked Dec 31 '17 11:12

tomJO


Video Answer


1 Answers

Without seeing what you are doing, it's quite difficult to know exactly what you are trying to achieve. Generally, you should not be handling watchers yourself, so it's worth taking a look at your code to see if there is a better solution. With that said, it is possible to apply a watcher at runtime, you can do it inside the mounted hook, after you have initialised everything else:

new Vue({
  el: '#app',
  created() {
    // this won't fire the watcher as it hasn't been applied yet
    this.foo = 'foo'
  },
  mounted() {
    // Apply watcher after all other initialization is done
    this.applyFooWatcher()
  },
  methods: {
    applyFooWatcher() {
      this.$watch('foo', function(newVal, oldVal) {
        console.log('Foo changed from ' + oldVal + ' to ' + newVal);
      });
    }
  },
  data: {
    foo: ''
  }
})

Here's the JSFiddle: https://jsfiddle.net/fo0vmxf6/

like image 69
craig_h Avatar answered Oct 18 '22 04:10

craig_h