vue2.0 watch

Vue official website explanation: An object, the key is the expression to be observed, and the value is the corresponding callback function. The value can also be a method name, or an object containing options. The Vue instance will call $watch() on instantiation, iterating over every property of the watch object.

That is to say, the watch can monitor the changes of the object, and the rules are key-value pairs.

export default {
    props: {
      fatherAjaxData: {
        type: Object
      }
    },
    data() {
      return {
        a: 1,
        b: 2,
        c: 3
      }
    },
    watch: {
      // The data props loaded asynchronously by the parent is given to the current child
      fatherAjaxData: function (val, oldVal) {
        this.$nextTick(() => {
          console.log('Listen to the existing value of fatherAjaxData data that has been loaded asynchronously');
        });
      },
      a: function (val, oldVal) {
        console.log(`watch a val change --- new val: ${val}, old val: ${oldVal}`);
      },
      // watch_b_val_change method name
      b: 'watch_b_val_change',
      c: {
        handler: function (val, oldVal) {
          console.log(`watch c val change --- new val: ${val}, old val: ${oldVal}`);
        },
        deep: true // In order to detect changes in the internal value of the object, you can specify deep: true in the options parameter. Note that listening for changes to the array does not require this.
      }
    },
    mounted() { // vue life cycle method vue page is fully loaded (excluding asynchronous data)
      this.$nextTick(() => {
        console.log('vue page loaded!');
      });
    },
    methods: {
      watch_b_val_change(val, oldVal) {
        console.log(`watch b val change --- new val: ${val}, old val: ${oldVal}`);
      }
    }
  };

 this.$nextTick :vue life cycle method executes the callback method of $nextTick when the data changes and the dom changes

deep: In order to detect changes in the internal value of the object, you can specify deep: true in the options parameter. Note that listening for changes to the array does not require this.

vm.$watch('someObject', callback, {
  deep: true
})
vm.someObject.nestedValue = 123
// callback is fired

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326270460&siteId=291194637