Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 613
Jarvis Avatar asked Dec 13 '17 19:12

Jarvis


People also ask

How do I watch data changes on Vue instance?

Using watchers in Vue # vue file we can watch for changes in data or props by using watch . For example, the below code will watch for a change in the data element pageData , and run a function according to the value it is changed to.

What is the life cycle of Vue component?

Each Vue component instance goes through a series of initialization steps when it's created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.

What is $El in Vue?

The $el option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this. $el. querySelector is used to access HTML elements and modify the element's properties.


1 Answers

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://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();
          }
      }
  }
});
like image 98
kmc059000 Avatar answered Oct 03 '22 23:10

kmc059000