最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I disable vue.js watcher while createdmounted methods are yet to be finished? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Dec 31, 2017 at 11:34 tomJOtomJO 3713 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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/fo0vmxf6/

发布评论

评论列表(0)

  1. 暂无评论