• This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

The listener

Listen for properties, respond to changes in data (data&computed), and execute functions immediately when the data changes.

Value types

Function types

Ex. :

const vm = new Vue({
  el: '#app'.data: {
    msg: 'Hello, hello, I'm Shan Shan',},watch: {
    msg () {
      console.log('MSG value changed ~'); }}})// Change the MSG value
vm.msg = 'hello~~~~';  // This will print 'MSG value changed' in the console
Copy the code

The listener function takes two arguments, the first being newVal(the changed data) and the second oldVal(the value before assigning the new value). As in the code above, change the listener Watch as follows:

watch: { msg (newVal,oldVal) { conosle.log(newVal, oldVal); }}// Change the MSG value
vm.msg = 'hello~~~~';  // It will print 'hello, hello, I am Shanshan hello~~~~' in the console
Copy the code

String type

Value is the name of the method that is executed when the data being listened for changes.

const vm = new Vue({
  el: '#app'
  data: {
    msg: 'very'
  },
  watch: {
    msg: 'msgChange'
  },
  methods: {
    msgChange () {
      console.log('MSG has changed');
    }
  }
})
vm.msg = 'hello';  // The msgChange function will be executed and the console will print 'MSG has changed'
Copy the code

Object type

When written as an object type, options can be provided.

handler

A necessity. Handler A callback function that is executed when the data being listened for changes. Handler’s value type is function/string, which, when written as a string, is the name of a method.

const vm = new Vue({
  el: '#app'
  data: {
    msg: 'very'
  },
  watch: {
    msg: {
      handler () {
        console.log('MSG has changed');
      }
    }
  }
})
vm.msg = 'hello';  // The callback will execute and the console will print 'MSG has changed'
Copy the code

deep

By default, a listener listener listens for reference changes only, and it can only be listened for when an object is assigned a value. Use the deep option to detect changes in the object’s internal values. Set deep to true, and the object will be listened to no matter how deep it is nested.

const vm = new Vue({
  el: '#app'
  data: {
    personObj: {
      name: 'Ming'.age: 88}},watch: {
    personObj: {
      handler () {
        console.log('Object's value has changed'); },deep: true    // Enable deep listening
    }
  }
})
vm.obj.name = 'the old Ming';  // The callback function is executed and the console prints' The value of the object has changed '
Copy the code

Note that the performance overhead is high when the object has a large number of properties. You can listen for one of the properties of the object, which will be discussed later.

immediate

With the immediate option, the callback will be invoked immediately after the listening starts. Rather than waiting for the listening data to change.

const vm = new Vue({
  el: '#app'
  data: {
    msg: 'very'
  },
  watch: {
    msg: {
      handler () {
        console.log('Callback function executed');
      },
      immediate: true}}})// If MSG is not changed at this time, the console will print 'callback function executed'
Copy the code

An array type

You can write many different value types in an array. Such as:

const vm = new Vue({
  el: '#app'
  data: {
    msg: 'very'
  },
  watch: {
    msg: [
      'msgChange'.function () {},
      {
        handler () {},
        deep: true.immediate: true}]}})Copy the code

Key type

Normal object key value

All the above are normal object keys and will not be described here.

The value is a string key

When the key type is a string, you can implement a listening for one of the properties of the object, for example:

const vm = new Vue({
  el: '#app'
  data: {
    personObj: {
      name: 'Ming'.age: 88}},watch: {
    'personObj.name' () {
      console.log('Object's value has changed');
    }
  }
})
vm.obj.name = 'the old Ming';  // The callback function is executed and the console prints' The value of the object has changed '
Copy the code

vm.$watch

The Vue instance will call $watch at instantiation time, iterating through each property of the Watch object. We can also use vm.$watch for listening, which is the same as the watch options section, but slightly different. The following is how to use it.

  1. Listen for changes to some data
 // 1. Three parameters, one of which is the monitored data; The second argument is the callback function executed when data changes; Three parameter optional, is the set option object
vm.$watch(
  'msg'.function () {
     // I've been up to something
  }, 
  {
    deep: Boolean.immediate: Boolean})// 2. Two parameters, one of which is the monitored data; The handler attribute is required and is the callback function executed when data changes. Other attributes are optional.
vm.$watch(
  'msg', 
  {
    handler () {
       // I've been up to something
    },
    deep: Boolean.immediate: Boolean})Copy the code
  1. Listen for changes to properties of an object
vm.$watch('obj.name'./** and */ above )
Copy the code
  1. The first parameter can be written as a function type when the listening data is initially uncertain and obtained from multiple data
vm.$watch(function () {
   This function is called every time the expression 'this.a + this.b' yields a different result
   // This is like listening on an undefined computed property
  return this.a + this.b;
},  /** The same parameter as above */ )
Copy the code

When the listener function executes, it returns an unlistener function to stop firing the callback:

const unwatch = vm.$watch('msg'.function () {});
unwatch();  // The MSG data listening will be cancelled after execution
Copy the code

When using unwatch, it is important to note that with the immediate option, you cannot cancel listening on the first callback.

const unwatch = vm.$watch('msg'.function () {
     // Did something
    unwatch();   // An error will be reported}, {immediate: true}})Copy the code

If you still want to use an unlistening function inside a callback, check its availability first:

var unwatch = vm.$watch('msg'.function () {
     // Did something
    if(unwatch) {
      unwatch();  
    }
  },{
    immediate: true}})Copy the code

Listener vs compute properties

  1. Both can observe and respond to changes in data on Vue instances.
  2. Watch excels at situations where one piece of data affects multiple pieces of data. Computational properties are good at dealing with scenarios where multiple data affects one data.
  3. Asynchrony can be performed in listeners, but not in computed properties, for example:

Using listeners:

var vm = new Vue({
  el: '#app'.data: {
    question: ' ',},watch: {
    question () {
      setTimeout(() = > {
        alert(this.question);
      }, 1000)}}})Copy the code

Exercise _ Imitation baidu search association

Url: sp0.baidu.com/5a1Fazu8AA5…

Request method: JSONP

Send parameters:

  1. Wd: string, search text
  2. Cb: a string, the name of the callback function

Result :(in JSON format)

{q: String, p: Boolean, s: Array}Copy the code

The last

If it is helpful to you, I hope I can give 👍 comment collection three even!

Bloggers are honest and answer questions for free ❤

  • Welcome to discuss in the comments section, the excavation officials will draw 100 nuggets in the comments section after the end of the Excavation project activity, see the details of the lucky draw in the event article, friends to discuss!!