如何使用vue js检查组件中数据何时自行更改?

时间:2017-12-13 19:58:05

标签: javascript methods vue.js components

我有自己更改数据的方法,简单示例:

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

如何使用正确的方法vue js创建这样的观察者? 或者我需要在组件中使用道具观看它?

1 个答案:

答案 0 :(得分:9)

Vue组件可以具有watch属性,该属性是一个对象。对象键需要是需要监视的prop或数据的名称,值是在数据更改时调用的函数。

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