Suppose the following code:

<div>
      <p>FullName: {{fullName}}</p>
      <p>FirstName: <input type="text" v-model="firstName"></p>
</div>new Vue({ el: '#root', data: { firstName: 'Dawei', lastName: 'Lou', fullName: '' }, watch: { firstName(newName, oldName) { this.fullName = newName + ' ' + this.lastName; }}})Copy the code

The effect of the above code is that when we enter firstName, Wacth listens for the new value of each change and evaluates the output fullName.

The handler method and the immediate attribute

One of the features of watch here is that it does not perform at the initial binding, but does not perform the listening calculation until the firstName changes. What if we wanted it to be changed right from the start when it was originally bound? We need to modify the writing method of our watch. After modification, the code of watch is as follows:

watch: {
  firstName: {
    handler(newName, oldName) {
      this.fullName = newName + ' ' + this.lastName;
    },
    / / on behalf of the statement in the wacth firstName immediately after this method to execute the handler method first
    immediate: true}}Copy the code

“FirstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”, “firstName”.

Immediate :true means that if firstName is declared in wacth, the handler method in wacth will be executed immediately. If false, the handler method will not be executed at binding time.

Deep attribute

Watch also has a property called “deep”, which defaults to false to indicate whether it is listening deeply. For example, we have a property called “obj” in our data:

<div>
      <p>obj.a: {{obj.a}}</p>
      <p>obj.a: <input type="text" v-model="obj.a"></p>
</div>

new Vue({
  el: '#root',
  data: {
    obj: {
      a: 123
    }
  },
  watch: {
    obj: {
      handler(newName, oldName) {
         console.log('obj.a changed');
      },
      immediate: true
    }
  } 
})
Copy the code

When we entered the data view in the input box to change the value of OBJ. a, we found that it was invalid. Due to the limitations of modern JavaScript (and the deprecation of object.Observe), Vue cannot detect the addition or removal of Object properties. Since Vue performs a getter/setter transformation on the property when initializing the instance, the property must be present on the data object for Vue to transform it in order for it to be responsive.

By default, the handler listens only for references to obj. It listens only when we assign a value to obj. For example, when we reassign obj in the Mounted event hook function:

mounted: {
  this.obj = {
    a: '456'}}Copy the code

Then our handler will execute, printing OBJ. a changed.

Conversely, what if we need to listen for the value of the property a in obj? This is where the deep property comes in!

watch: {
  obj: {
    handler(newName, oldName) {
      console.log('obj.a changed');
    },
    immediate: true.deep: true}}Copy the code

Deep means to look deep, and the listener is going to go through all the layers, adding this listener to all the properties of the object, but the performance overhead is very high, and any modification to any property in obj will trigger the handler in that listener.

Optimization, we can be using string form listening.

watch: {
  'obj.a': {
    handler(newName, oldName) {
      console.log('obj.a changed');
    },
    immediate: true.// deep: true}}Copy the code

So vue.js will parse through the layer by layer until it encounters the property a, and then it will set the listener function for A.

The cancellation of watch

Why log off watch? Because our components are often destroyed, for example, if we hop a route and jump from one page to another, then the watch on the original page is actually useless. At this time, we should log off the watch on the original page, otherwise it may cause the built-in overflow. Fortunately, we usually write the watch in the component option, it will be destroyed along with the component destruction.

const app = new Vue({
  template: '<div id="root">{{text}}</div>'.data: {
    text: 0
  },
  watch: {
    text(newVal, oldVal){
      console.log(`${newVal} : ${oldVal}`); }}});Copy the code

However, if we write watch as follows, then we need to manually log out, which is actually quite simple

const unWatch = app.$watch('text', (newVal, oldVal) => {
  console.log(`${newVal} : ${oldVal}`);
})

unWatch(); // Log out of the watch manually
Copy the code

App. $watch returns a value, which is the unWatch method. To log out of your watch, just call the unWatch method.

To the end.


This article was first published on the public account “Front-end Full Stack Developer” ID: by-zhangbing-dev. The first time to read the latest article, will give priority to two days to publish new articles. Concern after the private message reply: gift package, send a network high-quality video course network disk data, can save a lot of money for you!