javascript 如何使用vue js检查组件中的数据何时发生变化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47801200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:36:13  来源:igfitidea点击:

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

javascriptmethodsvue.jscomponents

提问by Jarvis

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?

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

回答by kmc059000

Vue components can have a watchproperty 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.

Vue 组件可以有一个watch属性,它是一个对象。对象key需要是需要监听的prop或数据的名称,value是数据变化时调用的函数。

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

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