Search code examples
javascriptmethodsvue.jscomponents

How to check when data changes in component by itself with vue js?


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?


Solution

  • 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();
              }
          }
      }
    });