16

I have method that changes data in itself, simple example:

Vue.component('component', {
  template: '#component',
  data: function () {
    return {
      dataToBeWatched: ''
    }
  },
  methods: {
    change: function (e) {
      var that = this;
      setTimeOut(function() {
        that.dataToBeWatched = 'data changed';
      }, 2000);
    },
    makeSmthWhenDataChanged: function () {
      // ajax request when dataToBeWatched changed or when dataToBeWatched isn't empty
    }
  }
});

How to create such watcher using correct methods vue js? Or I need to use props watching it in component?

1 Answer 1

36

Vue components can have a watch property which is an object. The object keys need to be the name of the prop or data that needs to be watched, and the value is a function that is invoked when the data changes.

https://v2.vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property

Vue.component('component', {
  template: '#component',
  data: function () {
    return {
      dataToBeWatched: ''
    }
  },
  methods: {
    change: function (e) {
      var that = this;
      setTimeOut(function() {
        that.dataToBeWatched = 'data changed';
      }, 2000);
    },
    makeSmthWhenDataChanged: function () {
      // ajax request when dataToBeWatched changed or when dataToBeWatched isn't empty
    }
  },
  watch: {
      dataToBeWatched: function(val) {
          //do something when the data changes.
          if (val) {
              this.makeSmthWhenDataChanged();
          }
      }
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I knew it should be simple!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.